Is there a difference between `new Image()` and `document.createElement('img')`?
Asked Answered
H

6

80

In javascript, I can do:

img1 = new Image();
img2 = document.createElement('img');

my question is, is there a difference between the two approach? I've read somewhere that Image, Form, and Element is called host objects, is this true? If it is, what are host objects?

Which approach is preferable?

Hibernia answered 5/6, 2011 at 8:15 Comment(1)
Where new Image is defined?Worthy
E
63

I couldn't find any detailed reference but based on the comment in the MDC - HTMLImageElement example, it seems that Image is part of DOM level 0 whereas document.createElement is part of DOM level 2.

DOM level 0 was invented by Netscape and provided a way to access the certain elements of the website. Basically all browsers support it for backwards compatibility.
But to be honest, I don't understand why the Image constructor exists there, because, as far as I understood it, there was no way to manipulate the document with DOM level 0. Maybe it was only used internally by the browser to create the objects.

DOM level 2 is an official standard developed by the W3C.

For more information about the DOM levels, have a look at at quirksmode.org - Level 0 DOM and Wikipedia.


I've read somewhere that Image, Form, and Element is called host objects, is this true?

Yes.

If it is, what are host objects?

The ECMAScript specification motivates host objects this way:

ECMAScript is an object-oriented programming language for performing computations and manipulating computational objects within a host environment. ECMAScript as defined here is not intended to be computationally self-sufficient; indeed, there are no provisions in this specification for input of external data or output of computed results. Instead, it is expected that the computational environment of an ECMAScript program will provide not only the objects and other facilities described in this specification but also certain environment-specific host objects, whose description and behaviour are beyond the scope of this specification except to indicate that they may provide certain properties that can be accessed and certain functions that can be called from an ECMAScript program.

and

host object
object supplied by the host environment to complete the execution environment of ECMAScript.
NOTE Any object that is not native is a host object.

So any object that is not defined in the specification and provided by the environment is a host object. These are for example in a browser (among others): window, document and console.

Embrue answered 5/6, 2011 at 8:56 Comment(5)
Nice answer! I wanted to ask, why is document considered host object? Isn't it defined in DOM level 1 spec? w3.org/TR/REC-DOM-Level-1/level-one-core.html#i-DocumentDistribution
@rickchristie: Don't confuse the DOM specification with the ECMAScript specification. document is provided by the browser as an interface for JavaScript to access the DOM. It is not part of the ECMAScript specification (of JavaScript itself).Embrue
DOM0 is an informal name given to pre-DOM level 1 methods of manipulating the document in browsers. Using the Image constructor was primarily used to "preload" images used dynamically within the page into the browser cache, typically for image switching effects such as rollovers. It originated in Netscape 3, which provided a very limited range of mechanisms for dynamic document manipulation (image switching, form element manipulation and form submission, and updating the status bar text, as I remember it).Sundown
So, which is "better" for loading, caching, manipulating images before displaying them?Inlay
This is a pretty good answer as are some of the others below, but they all seem incomplete. Taken together, I think the true differences might be revealed by creating each object, 1) doing a recursive dump of all properties and methods to conpare them, 2) to watch network logs to verify if the caching behavior is the same, and 3) test event propagation, as one answer suggested that there may not be any (or not correct) event propagation to Image. This is probably the result of a non-standardized feature like Image. 4) One answer poses a case where Image maybe desired but it maybe a code smell.Clemmie
B
21

Requirements:

In my team, we are building angular 5 application. The feature requirement was to preload images on component load, in order to reuse the them without loading again when needed in specific place in our Single Page Application.

1. img = new Image(); way:

We tried preloading images in DOM by create new Image() but when we reused the image src URL, the browser always reloaded the source file or checked if the header is modified (if cache enabled) which means preloading was sucessful but for every reuse, the roundtrip to server was made again.

2. img = document.createElement('img') way:

When we did the same with document.createElement('img') the image source was not reloaded, rather reused from local memory of the document and no extra request was made for the img src URL.

I do not really understand why, but this is a major difference that we discovered. In case anyone else needs to reuse the Preloaded images, the later would be the way to go to save some bandwith and few request roundtrips :)

Booma answered 19/6, 2018 at 14:42 Comment(1)
Yeah, I'm definitely seeing some big differences between the two when using them with web components. Relevant question.Owades
M
11

The two lines are equivalent and both create HTMLImageElement object. The only difference is in XML document with mixed namespaces - new Image() always returns <img> element with XHTML namespace, document.createElement('img') doesn't always do this.

Medea answered 5/6, 2011 at 8:20 Comment(2)
Thanks! Can you elaborate more why document.createElement('img') doesn't always do that (is it depending on the doctype of the document)?Hibernia
Regarding the namespace: That's what document.createElementNS is for: developer.mozilla.org/en/DOM/document.createElementNSEmbrue
C
4

I personally would stick with createElement because then its not a special case to make an image everything is made the same way as they are identical I also noticed that jquery use appendChild(node) method for everything and I'm not sure of the difference between that and the two methods in your questions but jquery does work cross browser

Cordovan answered 5/6, 2011 at 8:48 Comment(0)
C
3

I don't know what the technical difference should be, but I just fixed in IE8 bug by changing from new Image() to document.createElement('img') in the following code. In IE8, the onload callback never fired when using the Image constructor.

newImage = document.createElement('img');
//newImage = new Image();

newImage.onload = function () {
  callback(this.width, this.height);
};

newImage.src = image.src;
Casilde answered 26/8, 2015 at 13:19 Comment(0)
O
1

There are some significant differences between those two ways of creating images when you're working with Web Components. For example, if you use the document.createElement approach from within an imported HTML document (using <link rel="import" href="...">), then the image isn't actually loaded until it has been appended to the main document's DOM. See this SO question/answer for more details.

Owades answered 15/9, 2018 at 15:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.