Reputation: 1382
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?
Upvotes: 3
Views: 79
Reputation: 2429
When creating a script element dynamically, the source file will not be loaded or executed before the element has been inserted into the document. Loading of a script is asynchronous. This means your code does the following:
Edit: Thanks for pointing out that setting the async 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. I made an example to show this.
Upvotes: 4
Reputation: 1751
Javascript runs top to bottom unless it's a function, an asynchronous call to a server, or in a closure that waits for some event (ie: window.load()
)
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.
You can insert breakpoints in Firebug and Chrome Dev tools to step through your scripts and see what is happening too. More Info: https://developers.google.com/chrome-developer-tools/docs/javascript-debugging
Upvotes: 1