How to preload an image in JavaScript or HTML code?

Often times, we need to “preload” an image into browser’s cache for performance concern. For instance, we have a mouseover event and the image needs to be update without any delay. This “Preloading” stuff can be achieved in two ways , either JavaScript or HTML code.

Javascript

We can “preload” an image with the following Javascript.


<script type="text/javascript">
if (document.images) {
    imgPreload = new Image();
    imgPreload.src = "/preload-image.jpg";
}
</script>

We also can “preload” few images with the following Javascript.


<script type="text/javascript">
if (document.images) {
    imgPreload1 = new Image();
    imgPreload1.src = "/preload-image1.jpg";
    imgPreload2 = new Image();
    imgPreload2.src = "/Preload-image2.jpg";
}
</script>

HTML

What about Javascript is disabled? Here is another dirty trick in HTML. Just load an image and hide it by specified the width and height equal = 1 :), who bother?


author image

mkyong

Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities. Read all published posts by

Comments

avatar
newest oldest most voted
trackback
How do preload an image in JavaScript or HTML code? | Javascript

[…] is the original: How do preload an image in JavaScript or HTML code? | Javascript SHARETHIS.addEntry({ title: "How do preload an image in JavaScript or HTML code? | Javascript", […]

TCP
Guest
TCP

very cool & simple tip, thank you very much for sharing.

Thank

Tony
Guest
Tony

Another way to preload images is to use CSS. This may be benificial as javacsript is not enabled on all browsers. For examples of how to do this visit: http://www.prismgraphicdesign.co.uk/blog/?p=12

Alice Kinston
Guest
Alice Kinston

Oh my goodness! a tremendous article dude. Thanks However I’m experiencing concern with ur rss . Don’t know why Unable to subscribe to it. Is there anyone getting identical rss problem? Anybody who knows kindly respond. Thnkx