5

I want to load the image after the image is completely loaded or downloaded in the browser. I dont want to display the image while it is being downloaded. Rather I would like to display a lower quality version of that image until the high quality images is loaded in the background, and when the image is completly loaded in the background, I want to replace the lower quality image with that image.

I have two images, say

$LQimage = "LQabc.jpg";

$HQimg = "HQabc.jpg";

How can I make it work?

EDIT With the answer posted by @codebox, this code worked.. thanks :)

<html>
<head>
<script type="text/javascript">
function load(){
    var img = new Image();
    var imgUrl = 'HQabc.jpg';
    img.onload = function(){
        // this gets run once the image has finished downloading
        document.getElementById('pp').src = imgUrl;
    }
    img.src = imgUrl; // this causes the image to get downloaded in the background
}
</script>
</head>
<body onload="load()">
    <img id="pp" src="LQabc.jpg" width=600/>
</body>
</html>

1 Answer 1

5

This should do it:

function preLoadImage(){
    var img = new Image();
    var imgUrl = 'HQabc.jpg';
    img.onload = function(){
        // this gets run once the image has finished downloading
        document.getElementById('idOfImgElement').src = imgUrl;
    }
    img.src = imgUrl; // this causes the image to get downloaded in the background
}

If you run this function once the page has loaded it should work:

<body onload="preLoadImage()">
2
  • It is still not working.. can u help me out.. I have posted my code in the EDITED section of my question Sep 6, 2012 at 8:35
  • You need to make sure that the JavaScript code only runs once the page has loaded, put the code into a function and call it from body onload() - apart from that it looks ok
    – codebox
    Sep 6, 2012 at 8:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.