Javascript document write overwriting page?

Using document.write() after the page has finished loading implicitly calls document.open(), which creates a new page. You should generally avoid document.write() and stick to proper DOM creation techniques, or use jQuery’s shorthand creation methods:

jQuery(function($) {
    $('<style type="text/css"> .preload img { display: none; } </style>')
        .appendTo("head");
    $('#body-wrap').preloadThis();
});

I’m assuming you can’t edit the HTML or CSS files that are loaded by the page to include this rule? If that’s the case, and you want these styles applied before the page finishes loading, take `document.write()` out of the jQuery ready handler:

// write() before the document finishes loading
document.write('<style type="text/css"> .preload img { display: none; } </style>');
jQuery(function($) {
    $('#body-wrap').preloadThis();
});

This will write the <style> tag immediately after the currently executing <script> tag. Hopefully, this is in your <head> element as <style> is invalid anywhere else, although all browsers should parse it OK either way.

Leave a Comment