3

If I do like that:

var img = new Image();
img.src = "2016-10-26_6-57-53.png";

Chrome sends a request to an image even before it's appended to the DOM.

It doesn't happen with the script:

var oScript = document.createElement("script");
oScript.src = "main.js";

Why the different behavior for the image?

Max Koretskyi
  • 101,079
  • 60
  • 333
  • 488
  • `Image` is not a `HTMLElement` like `script`. `img` is and it will behave the same as script... – marekful Nov 24 '16 at 20:15
  • http://stackoverflow.com/questions/6241716/is-there-a-difference-between-new-image-and-document-createelementimg – marekful Nov 24 '16 at 20:20
  • @marekful: `HTMLElement.prototype.isPrototypeOf(Image.prototype); // true` –  Nov 24 '16 at 20:21
  • You are right. Image is HTMLElement... Image is the older standard and it has event handlers for onload, onabort and onerror while createElement('img') does not. It was probably kept for convenience? – marekful Nov 24 '16 at 20:24
  • 1
    @marekful: I'm not sure what you're getting at. They both create the same kind of object. https://jsfiddle.net/7Lr27xdy/ In any case, the question is about the difference between an image and a script. –  Nov 24 '16 at 20:32
  • Only with an instance of `Image` you can listen for those events not with `createElement('img')` – marekful Nov 24 '16 at 20:34
  • 1
    @marekful: The jsfiddle I posted shows both responding to the `onload` event. They're the same kind of object, so they both exhibit the same behaviors. –  Nov 24 '16 at 20:38
  • https://www.w3.org/TR/html5/embedded-content-0.html#update-the-image-data https://www.w3.org/TR/html5/scripting-1.html#prepare-a-script – Annarfych Nov 24 '16 at 23:56
  • Basically the standard assumes that script can be not inserted and prefetch will be wasted but image probably will be inserted and should be prefetched even if not inserted. – Annarfych Nov 25 '16 at 00:02

0 Answers0