Javascript document writes overwrite page?

I am very new to javascript.

I am trying to create a tag using document.write (using Wordpress) to add a style that hides images before preloading them. I had to resort to writing Javascript style to hide images before loading them through CSS. I don’t want to write it to a CSS file if the user has Javascript disabled and then the images will never be displayed.

I am 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 just rewrites the whole page and makes it blank. How can i stop this? I want to add a tag to without deleting the page. Tried to use 'return', no luck.

Sorry, I'm new. Thanks in advance.

+7
javascript coding-style
Dec 23 '10 at 16:08
source share
2 answers

Using document.write() after the page has finished loading, implicitly calls document.open() , which creates a new page. Normally you should avoid document.write() and stick to the proper DOM creation methods or use jQuery short string creation methods:

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

<h / "> I assume that you cannot edit the HTML or CSS files uploaded by the page to include this rule? If this is the case and you want these styles applied before the page has finished loading, please remove document.write() from the jQuery 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> immediately after the current <script> . I hope this is in your <head> element, since <style> not valid anywhere, although all browsers should parse it anyway.

+18
Dec 23 '10 at 16:12
source share

You do not need to add the <style> , you can just hide them with jQuery:

 jQuery(function($) { $('.preload img').hide(); $('#body-wrap').preloadThis(); }); 

I don't know how your preloadThis() function preloadThis() , but I assume that it loads images and removes the .preload class from the img container. If this is true, this code will not help you - the images will be hidden.

+3
Dec 23 '10 at 16:13
source share



All Articles