Why are external js scripts often loaded with document.write () at the bottom of the HTML page?

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")); 

It would just be useful to replace document.write () with a literal value:

 <script type="text/javascript" src="http://www.google-analytics.com/ga.js"> 

? I assume that the tag is output with document.write () only because the value of gaJsHost ( 'http://www.' ) Is not known in advance. But if that were known, was there any reason to output the script tag with document.write () rather than include it literally?

+4
source share
5 answers

The default scripts, when they appear on the html page, block the rest of the page upon loading. Only when they have finished loading and executing does the rest of the page continue to load. From high-performance Javascript from Nicholas K. Zakas :

This is an integral part of the page life cycle, as the script can lead to page changes at runtime. A typical example is using document.write () in the middle of the page (how often ads are used).

By inserting a script dynamically, as done above, you can overcome this behavior - without blocking the page - loads occur asynchronously.

By placing the object at the bottom of the page, you will see that html and css are loaded before javascript. Thus, while javascript is loading, the user can already see the page.

All about performance.

+3
source

so that the browser loads them after the page is displayed.

This is performance.

+2
source

There are several possible reasons: 1. Make sure that some part of the DOM already exists on the page before loading the javaScript file. This prevents you from manipulating unsorted DOM elements. 2. Speed ​​up the material; browsers usually go into single-threaded mode when loading javaScript, so it is better to delay it if it is not really needed at the beginning.

0
source

I would call a great resource about this in the first place:

http://webreflection.blogspot.com/2009/12/documentwriteshenanigans.html

So, after reading this, I see that the script loads after the page loads.

0
source

This is the fastest way to add script-generated text to the page [the browser does not need to change the structure of the DOM]. Used to insert ad scripts [crash if ad server is slow]. Adding user-generated user data to url.Prevents caching by adding random values.

mainly used for its speed.

0
source

Source: https://habr.com/ru/post/1435996/


All Articles