Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
766 views
in Technique[技术] by (71.8m points)

coding style - Javascript document write overwriting page?

I'm very new with javascript.

I'm trying to create a tag using document.write (with Wordpress) to add a style that hides images before they are preloaded. I've had to resort to writing a Javascript style to hide the images before they are loaded via CSS. I don't want to actually write it into the CSS file incase the user has Javascript disabled and then the images would never show.

I'm trying to get this code to work:

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

But, it is just overwriting the whole page and making it go blank. How can I stop this? I want to add the tag to the without removing the page. Tried using 'return', no luck.

Sorry, I'm a novice. Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...