Note that there are some explanatory texts on larger screens.

plurals
  1. PODynamically adding javascript to <head>
    primarykey
    data
    text
    <p>I am using a function "loadScript" to insert an external .js if the browser detects it is online.</p> <pre><code>&lt;script type="text/javascript"&gt; function loadScript() { if (navigator.onLine == true) { var src = "js/getdata.js"; var script = document.createElement("script"); script.type = "text/javascript"; script.src = src; document.getElementsByTagName("head")[0].appendChild(script); } } &lt;/script&gt; </code></pre> <p>It all works fine except that the final script appears as...</p> <pre><code>&lt;script type="text/javascript" src="js/getdata.js"&gt; function getData() // get MySQL data from db { &lt;?php $dbopen = 0; // database flag $con = mysql_connect("website.co.uk","guest","password"); mysql_select_db("DB", $con); if (!$con) {die('Could not connect: ' . mysql_error());} else {$dbopen = 1;} ?&gt; </code></pre> <p>etc...</p> <p>And the Firebug console tells me the function getData is not defined and the content </p> <pre><code>&lt;?php </code></pre> <p>is a syntax error...</p> <p>I would like to get the script into the head and have it defined as a usable function within the DOM.</p> <p>I would appreciate any thoughts you may have.</p> <p>GitaarLAB asked for the whole code, so here it is.</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;script type="text/javascript"&gt; function loadScript() { if (navigator.onLine == true) { var src = "js/getdata.js"; var script = document.createElement("script"); script.type = "text/javascript"; script.src = src; document.getElementsByTagName("head")[0].appendChild(script); } } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;script type="text/javascript"&gt; loadScript(); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>The output is...</p> <pre><code>&lt;script type="text/javascript" src="js/getdata.js"&gt; function getData() { &lt;?php $hhgopen = 0; $con = mysql_connect("website.co.uk","guest","password"); mysql_select_db("ThisDB", $con); if (!$con) { die('Could not connect: ' . mysql_error()); } else { $result = mysql_query("SELECT * FROM articles", $con); $numrows = mysql_num_rows($result); $hhgopen = 1; } ?&gt; } &lt;/script&gt; </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload