Lac Viet
Lac Viet

Reputation: 720

Preloading Image with src property

Having read many "preloading image using javascript" title on internet, I found the same solution. Here is a simple sample code to preload a image with "stuff.jpg" name:

 <script>
    var img = new Image();
    img.src = "stuff.jpg"
 </script>

However I find no source telling me what actually the "src" property does when defining it (e.g img.src = "stuff.jpg"). My thinking here is, it's just set "src" property to img by a string (that is "stuff.jpg") and not loaded the real image yet. But I am fairly reluctant about my thinking, because if it's right, then the code above will be worthless. Could you tell me what the src actually does in the above code and it would be great if you could give me a source for you explaination. Thank you.

Upvotes: 0

Views: 153

Answers (1)

Jaime
Jaime

Reputation: 6814

Yes, your code actually loads the image. Setting the src of an image object loads the image, now you just need to add the img to the DOM.

Something like:

var div = document.getElementById('theImg');
div.appendChild(img);

Of course doing it this way accomplishes nothing, but if the images are to be displayed in response to some event, a button click or something, then you actually pre-loaded the image.

You can test this by executing your code in Chrome and looking at the Network tab in the Developer Tools and see that the image is actually requested from the server, even if you don't add it to the DOM

Upvotes: 1

Related Questions