Delay/defer document.write from an external script till after document ready

2.1k views Asked by At

I have an external script which loads advertisements. The script being loaded includes calls to document.write. The problem is this delays the doc ready for the site. I would like to delay showing this until after the doc ready.

Currently I just tried wrapping the function that loads the external content in a jquery doc ready, but the page blows up. It goes to a all white screen with just the ad and some code showing.

Obviously this is because document.write is running after the page is loaded. Does anyone know a way around this or how to delay loading of the external content till after doc ready?

4

There are 4 answers

3
Annie On

You could try the hack where you override document.write and buffer the output, then write it to a div in doc ready.

0
Tom On

This has been solved for you:

by the fine people behind Postscribe

0
stealthyninja On

@jhanifen: My first thought was of the defer attribute, which I've used before specifically when I had issues with certain scripts in Internet Explorer that used document.write. I wasn't sure if it would work so well in the context of ads loaded from external sources so I did I search on SO for it and came across this question and accepted answer -- Is it possible to load a javascript ad last on the page to prevent slow load times? -- which may prove to be / or help you towards getting your own solution.

0
glen-84 On

I think this could work as well:

https://github.com/iamnoah/writeCapture

Utility to assist the Ajax loading of HTML containing script tags that use document.write