Avoid document.write (Deprecated)

What is the document.write Method?

The document.write is one of the methods to write text, or scripts, to a document stream. Anything you put in-between the parentheses will be written on the HTML document. Today’s browsers are much more advanced and use what is called speculative parsing. This allows the browser to “look ahead” at the next elements that need to be download from the DOM (Document Object Model), which helps make the page load more efficiently and quickly. The issue with this method is when render-blocking scripts or third-party scripts are written into document.write function. Everything the browser was doing must now stop, parse these scripts, then download them. And if there is another script after that, it must do this all over again until finished. This can have a drastic effect on load times, especially for users on slower connections.

How to Avoid the document.write Method

The recommendation from PageSpeed is to obviously avoid that method where possible, but instead call out the required resources in HTML itself. This allows the speculative parsers to do their jobs and properly look ahead at those resources. In cases where JavaScript is involved, lazy loading, or asynchronous loading techniques, can be utilized. Lazy loading allows the page to defer loading page elements until the user needs them. This improves performance and gives better overall experience to the user, allowing the browser to only download the necessary elements.

Additional Methods to Avoid document.write

Another method to help avoid the document.write method is to use what is known as friendly IFrames. This is used for situations where there may be some legacy code that cannot be loaded using these other recommended actions. Using friendly IFrames works by using an IFrame that shares the same domain as the page it is hosted on, making it trusted content and it can be manipulated beyond the IFrame window. A non-friendly IFrame is considered an IFrame hosted from a different domain and cannot be manipulated beyond the code in the IFrame window.



Lighthouse is an open-source tool that is used to run an audit against your web pages and provides scores and suggestions for improving page performance, accessibility, SEO, and more.


PageSpeed Terms

PageSpeed Insights is a tool created by Google that reports on the performance of a page on both mobile and desktop devices, and provides suggestions on how that page may be improved.



YSlow is an open-source website analysis tool that can be used to identify web page performance issues. Learn more about the YSlow to enhance your web pages and the user experience.