Question

The JS timer blanks all content on the page when it runs out.

window.setTimeout(function() {
document.write("<link rel='prerender' href='http://google.com' />")


}
,10000
); 

The effect happens both when the JS is placed within the head and in the body.

How do I do a prefetch/prerender based on a timer without having my page turned blank? (all content vanishes. there is no url redirection. i'm left with a blank page)

Was it helpful?

Solution

document.write can only be used before the document is ready for display. It should be used inline while it is building. If used after document is ready it will cause issues like your facing.

If you are using jQuery you can use their getScript function:

window.setTimeout(function() {

    $.getScript('script.js',function(){
       //this is your callback function to execute after the script loads
    });
}
,10000
); 

Or if using only javascript this question may be useful to you. They use:

(function(d, t) {
var g = d.createElement(t), // create a script tag
    s = d.getElementsByTagName(t)[0]; // find the first script tag in the document
g.src = 'your-script.js'; // set the source of the script to your script
s.parentNode.insertBefore(g, s); // append the script to the DOM
}(document, 'script'));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top