Preloading images via CSS

Why on earth would you want to add the css via js instead of normally in the css? You are just using JS to add CSS. Add the background images to the css rule and forget the JS.

If you want to ‘lazyload’ the images then you will need js but you will need some special JS that waits for all elements on the page to load and display and then once that has happened it will load the extra images afterwards -this is called lazy loading. Lazy loading is useful for images that are not to be shown initially when the page is loaded but might be called for later on (as in a rollover or hide and show).

The css version will load the images on page load and therefore may slow the initial page render down a little. (In html5 you can now add style tags inside the body element and although I dislike this it does mean that you can add a style tag before the closing body element and insert the css for the images and then they will get rendered last and not hold the page up.)

2 Likes