How to avoid the use of document.write?
Using document.write() to fetch external resources, especially early in the document, can significantly increase the time it takes to display a web page. Using document.write() from external JavaScript resources is especially expensive, since it serializes the downloads of the external resources. The browser must download, parse, and execute the first external JavaScript resource before it executes the document.write() that fetches the additional external resources. For instance, if external JavaScript resource first.js contains the following content:
The download of first.js and second.js will be serialized in all browsers.The browser is not able to continue the execution of first javacript file. The web browser is forced to wait for the second script to load AND to be executed and after that it will execute the first one. injecting a script by using document.write instruction causes severe issues about websites loading time.
Issues caused by document.write
When you use the following Javascript command to inject a script:
the browser is not able to continue parsing the HTML. The web browser is forced to wait for the resource to load AND to be executed. The situation could even be more harmful, as the browser will also be stopped if the first script injects other ones. Not such a rare situation considering all the third-party services you are probably using on your webpages.
Another issue to be considered about using document.write command not only in a script injection case is if the DOM tree has already been built, the use of document.write will force the browser to build it again and it will reset the current document.
How to avoid the use of document.write?
Generally, you should avoid the use of blocking JavaScript. Defer and async attributes will let you invoke external scripts asynchronously.
However, be careful regarding the execution order of your scripts, as this order is not guaranteed in an asynchronous loading case. If the use of document.write concerns a third-party service, you have to check if your provider propose an asynchronous loading version. If it doesn’t, then think about an alternative.
In order to insert contents in your web pages, prefer DOM manipulation rather than using document.write. Here is an example of script:
sNew.async = true;
sNew.src = “https://example.com/script.min.js”;
var s0 = document.getElementsByTagName(‘script’)[0];
s0.parentNode.insertBefore(sNew, s0);
[…] It then has to run the javascript to know what it needs. This is very wasteful as far as page speed goes because anything called by document.write can also be called via HTML (which displays much faster and is already downloaded). Since browsers can’t know what is being called, they will have to display the page slower. For more about document.write and how to avoid it go to our post How to avoid the use of document.write […]