Document.write method is slow

How to Avoid document write

In order to display or call anything via document.write a browser must take wasteful steps. It must download the resource, then read the resource, then it may have to call another resource just to do the whole thing again.

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.

Unlike an image, which the browser does not need to have downloaded to continue displaying a webpage properly (if width and height are used), document.write offers no such way for a browser to know what it will be doing or calling.
It is particularly bad for page speed if you are using it to call an external resource because a browser can't know what it is calling until it runs the script.
If you do not know what document.write is, you probably do not need to worry about it. However if you have received a warning from a web page speed test alerting you that you are using it, you should remove it and replace with basic HTML.

How to fix document.write

You will need to find the document.write call in your files, see what it is doing, then replace the calls it makes with HTML calls instead.
Finding it can be done by searching your html for "document.write". That is the easy part.
To see what it is doing you will have to read the code. Below is an example code where document.write is calling an external resource (exactly what you do not want).

document.write('<script src="another.js"></script>');

The above code is calling an external resource (another.js). This means that the browser has to read and run that just to know that it needs to go get "another.js". This wastes time and roundtrips and negatively affects your web page speed.
The solution in the above scenario would be to call the external resource "another.js" through an HTML call instead. Here is how that would look...

<script src="another.js"></script>

What does this do?

Calling an external resource using HTML allows the browser to know that it needs that resource much faster and will allow it to display your webpage quicker.

by Patrick Sexton