Reputation: 45642
An example of this is Google analytics:
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
Would it be just as good just to replace the document.write() with the literal value:
<script type="text/javascript" src="http://www.google-analytics.com/ga.js">
? I'm guessing that the tag is output with document.write() only because the value of gaJsHost ('http://www.'
) isn't known ahead of time. But if it was known, would there be any reason to output the script tag with document.write() instead of including it literally?
Upvotes: 4
Views: 227
Reputation: 15609
Scripts by default, when encountered on a html page, block the rest of the page from loading. Only when they've finished downloading and executing does the rest of the page continue to get loaded. From High Performance Javascript by Nicholas C. Zakas:
This is a necessary part of the page’s life cycle because the script may cause changes to the page while executing. The typical example is using document.write() in the middle of a page (as often used by advertisements).
By inserting the script dynamically, as is being done above, you can overcome that behaviour - no page blocking - the loads happen asynchronously.
By putting the thing at the bottom of the page, you ensure the html and css are loaded before the javascript. This way, while the javascript is loading, the user can already see the page.
It's all about performance.
Upvotes: 3
Reputation: 1579
It is the fastest way to add a script-generated text into the page[the browser doesnot have to modify the DOM structure].So used for inserting advertising scripts [downfall if ad server is slow].Adding user generated data to the url.Prevents caching by adding random values.
basically used for its speed.
Upvotes: 0
Reputation: 26086
I would refer to a great resource about that first:
http://webreflection.blogspot.com/2009/12/documentwriteshenanigans.html
So after reading this, I can see the advantage is script is loaded after the page has been rendered.
Upvotes: 0
Reputation: 947
There are a couple of likely reasons: 1. To ensure that some part of the DOM already exists on the page before the javaScript file is loaded. This prevents you from trying to manipulate uncreated DOM elements. 2. To speed up stuff; browsers typically go into single-threaded mode when loading javaScript so it is best to delay it if you don't really need it at the onset.
Upvotes: 0
Reputation: 10550
to ensure that the browser loads them after the page is rendered.
It is a performance thing.
Upvotes: 2