2

Here is the image-loading construction in js:

var img = new Image();
img.onload = function(){
    //do something
}
img.src = "path to image";

I'm curious way this works, that after assigning string to object some event is triggered. Could someone explain it to me?

2
  • 1
    FYI, new Image() is equivalent to document.createElement('img'). Commented Oct 20, 2012 at 22:24
  • This is very useful for making it cache images to be loaded later, like those used by hidden elements (hidden by either rule - visibility:hidden or display:none). Commented Oct 20, 2012 at 22:35

2 Answers 2

3

Image is a special object (known in the spec as a host object) whose implementation is provided by the browser. The constructor is actually returning a new HTMLImageElement.

Internally, the src property has a setter function. When you set the src, the browser begins fetching the image in the background. (The exact mechanism by which this happens varies from browser to browser.)

When the request for the image completes successfully, the browser fires the load event. (If unsuccessful, it will fire the error event.)

Sign up to request clarification or add additional context in comments.

Comments

0

When you assign a string to the src property of the Image object the browser sends a request for the image from the server specified in the URL that should be in that string.

When the response comes back from the server with a valid image, the load event is triggered, and the onload event handler is called.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.