Remove Render-Blocking JavaScripts and document.write()

14 views
Skip to first unread message

Matt May

unread,
Aug 13, 2013, 1:38:44 PM8/13/13
to page-spee...@googlegroups.com
I'm not a JavaScript expert, but having run Pagespeed on one of my websites I got the following error message
 
"Eliminate external render-blocking Javascript and CSS in above-the-fold content Your page has 1 blocking script resources and 1 blocking CSS resources."
 
Firstly I moved the offending JavaScript to just before the </body> tag but I still got the PageSpeed error message.
 
So next I tried implementing "Defer loading of JavaScript" solution suggested by PageSpeed here https://developers.google.com/speed/docs/insights/BlockingJS but all I got was a blank page.
 
After much digging I came across this excellent article about Deferred Javascript Loading where I found the problem...my deferred javascript uses document.write()
 
Apparently the deferred javascript loading method doesn't work if the deferred code includes document.write (it actually blanks the page in my case).
 
Does anyone have any alternatives if you want to defer JavaScript which uses document.write() ?
 
Many thanks
 

Thomas Hey'l

unread,
Aug 13, 2013, 2:12:38 PM8/13/13
to page-spee...@googlegroups.com
Hi Matt!

I never trusted the "defer" or "async" attributes very much ;-) .  You might instead want to use a minimalistic DomReady solution or something similar for the DomContentLoaded event (as explained in your example URL) and then inject your script using insertBefore().  Of course, document.write will then not work anymore.  As it should generally be avoided, try to create your content using the DOM and adding it to a predefined container with a specific id attribute.

Regards, Thomas

Patrick Sexton

unread,
Aug 13, 2013, 11:03:28 PM8/13/13
to page-spee...@googlegroups.com
Document write is bad to use, is it possible to get rid of it and then use the google recommended solution

Thomas Hey'l

unread,
Aug 17, 2013, 6:27:29 AM8/17/13
to page-spee...@googlegroups.com
Hi Pat!


Document write is bad to use, is it possible to get rid of it and then use the google recommended solution?

The most easy approach to convert document.write() within the <body> to a defer-compatible solution is to predefine a container with a specific id at the appropriate location for the content and to add the content using the innerHTML property.

When it comes to things in the head, you should use the classic DOM method document.createElement(), set the object's properties and inject it using insertBefore().
The good news is this will nowadays work with CSS, too, w.s., the CSS will also be applied after the DOMContent event.

Regards, Thomas
Reply all
Reply to author
Forward
0 new messages