Also, when is the code loaded, on setting the
.src attribute or on appending the element. To illustrate:
var test = document.createElement('script'); test.src = 'some_path'; // is code loaded here? document.head.appendChild(test); // or here? ... // or is it an asynch operation?Answer1:
When creating a script element dynamically, <strong>the source file will not be loaded or executed before the element has been inserted into the document</strong>. Loading of a script is <strong>asynchronous</strong>. This means your code does the following:<ol><li>Create the script element</li> <li>Assign a source attribute</li> <li>Place the element into the document</li> <li>Start loading the source file asynchronously</li> <li>When loaded, execute the script</li> </ol>
<strong>Edit:</strong> Thanks for pointing out that setting the <em>async</em> property does not have any effect on the loading behaviour of scripts. I never actually used it and assumed it would work, but it apparently does not. I removed the part claiming it would. <a href="http://jsbin.com/ivasobo/2/edit?js,console" rel="nofollow">I made an example to show this</a>.Answer2:
Your code is as follows:
var test = document.createElement('script'); //declare variable test to create script element test.src = 'some_path'; //define element with src attribute 'some_path' document.head.appendChild(test); //place script element in head block
Though I would recommend creating dynamic script blocks server-side to avoid complications due to exceptions and high-load/timeout possibilities.