Avoid document write

Heads up! This is a developer-level document. You need to be one or hire one to implement this optimization. It may require changes to code in your theme or a plugin.

What is document.write()?

document.write() is a JavaScript function that inserts HTML into the page wherever it’s executed.

How does document.write impact performance?

Every time document.write() function is executed, the browser blocks the render until document.write() finish the work and the HTML inserted with it is parsed. Normally, this JavaScript function is used to add assets like JavaScript, example:

document.write('<script src="https://mysuperadplugin.com/ad-inject.js"></script>');

In this example, the function blocks the page rendering until the injected script tag is parsed and the source is downloaded.

The more JavaScript code is added to the site, the more impact this will have on your site, if it is used multiple times it can add several valuable seconds to the page load.

If document.write() is used only once in the site code, normally there won’t be a big impact but Google Page Insights will continue to complain about this.

In any case, it is advisable to avoid using this to comply with Google Page Insights.

You can find out if your site has a document.write() execution in several ways :

Browser Console - Chrome

Google PageSpeed Audit / Lighthouse: Avoid document.write()

What can I do to avoid document.write() on my page?

This function is normally added by a plugin or your theme. In these cases the only thing you can do is either ask the original developers of the plugin / theme to fix this in the code or install an alternative that uses a different approach to add code to the HTML. This is related to how the code is written, so WP Rocket cannot fix this, but the original developer can. 

Tip: Ad plugins are the most common ones that add JavaScript files using document.write()

How does WP Rocket handle document.write?

WP Rocket excludes document.write() inline scripts from all our JavaScript optimizations to avoid issues. If this is delayed for example it can replace all the content of the resultant HTML because document.write() should be executed when the page is loading, in case that this is executed after the page loading, it will replace the entire HTML document (The entire page).

Example: 

Did this answer your question? Thanks for the feedback There was a problem submitting your feedback. Please try again later.