javascript `new Image()` 和 `document.createElement('img')` 之间有区别吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6241716/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 20:01:19  来源:igfitidea点击:

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

javascriptdom

提问by Iswanto Arif

In javascript, I can do:

在javascript中,我可以这样做:

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 Elementis called host objects, is this true? If it is, what are host objects?

我的问题是,这两种方法有区别吗?我在某处读到过ImageForm,Element被称为宿主对象,这是真的吗?如果是,什么是宿主对象?

Which approach is preferable?

哪种方法更可取?

采纳答案by Felix Kling

I couldn't find any detailed reference but based on the comment in the MDC - HTMLImageElementexample, it seems that Imageis part of DOM level 0 whereas document.createElementis part of DOM level 2.

我找不到任何详细的参考资料,但根据MDC 中HTMLImageElement的评论-例如,它似乎Image是 DOM level 0document.createElement的一部分,而是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 whythe Imageconstructor exists there, because, as far as I understood it, there was no way to manipulatethe document with DOM level 0. Maybe it was only used internally by the browser to create the objects.

DOM level 0 是由 Netscape 发明的,它提供了一种访问网站某些元素的方法。基本上所有浏览器都支持它向后兼容。
但说实话,我不明白为什么Image构造函数中存在那里,因为,据我的理解是,有没有办法来处理与DOM级别为0的文件也许它只是通过浏览器内部使用,以创建对象。

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

DOM 级别 2 是 W3C 制定的官方标准。

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

有关 DOM 级别的更多信息,请查看quirksmode.org - Level 0 DOMWikipedia



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

我在某处读到过ImageForm,Element被称为宿主对象,这是真的吗?

Yes.

是的。

If it is, what are host objects?

如果是,什么是宿主对象?

The ECMAScript specificationmotivates host objects this way:

ECMAScript规范能够激励主机对象是这样的:

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.

ECMAScript 是一种面向对象的编程语言,用于在宿主环境中执行计算和操作计算对象。此处定义的 ECMAScript 并非旨在计算自给自足;实际上,本规范中没有关于外部数据输入或计算结果输出的规定。相反,期望 ECMAScript 程序的计算环境不仅会提供本规范中描述的对象和其他设施,还会提供某些特定于环境的宿主对象,这些对象的描述和行为超出本规范的范围,除非表明它们可能提供某些可以访问的属性和可以从 ECMAScript 程序调用的某些函数。

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.

宿主
环境提供的宿主对象对象来完成ECMAScript的执行环境。
注意任何非本机对象都是宿主对象。

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, documentand console.

因此,任何在规范中未定义并由环境提供的对象都是宿主对象。例如,这些在浏览器中(以及其他):windowdocumentconsole

回答by duri

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.

这两行是等效的,都创建 HTMLImageElement 对象。唯一的区别在于具有混合命名空间的 XML 文档 -new Image()总是返回<img>具有 XHTML 命名空间的元素,document.createElement('img')并不总是这样做。

回答by Duplich

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.

在我的团队中,我们正在构建 angular 5 应用程序。功能要求是在组件加载时预加载图像,以便在我们的单页应用程序中的特定位置需要时重用它们而无需再次加载。

1. img = new Image(); way:

1. img = new Image(); 大大地:

We tried preloading images in DOM by create new Image()but when we reused the image src URL, the browser always reloadedthe 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.

我们尝试在 DOM 中预加载图像,create new Image()但是当我们重用图像 src URL 时,浏览器总是重新加载源文件或检查标头是否被修改(如果启用缓存),这意味着预加载成功但对于每次重用,到服务器的往返是再次制作。

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

2. img = document.createElement('img') 方式:

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 madefor the img src URL.

当我们document.createElement('img')对图像源做同样的事情时,没有重新加载,而是从文档的本地内存中重用,并且没有对 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 :)

我真的不明白为什么,但这是我们发现的一个主要区别。如果其他人需要重用预加载的图像,后者将是节省一些带宽和很少请求往返的方法:)

回答by mcgrailm

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

我个人会坚持使用 createElement 因为那样它不是制作图像的特例,一切都以相同的方式制作,因为它们完全相同我还注意到 jquery 对所有内容都使用 appendChild(node) 方法,我不确定两者之间的区别那以及您问题中的两种方法,但 jquery 确实可以跨浏览器工作

回答by Danny Tuppeny

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 Imageconstructor.

我不知道技术上的区别应该是什么,但我只是通过在以下代码中更改为new Image()来修复了 IE8 中的错误document.createElement('img')。在 IE8 中,onload 回调在使用Image构造函数时从未被触发。

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

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

newImage.src = image.src;

回答by Danny Tuppeny

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.createElementapproach 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/answerfor more details.

当您使用 Web Components 时,这两种创建图像的方法之间存在一些显着差异。例如,如果您document.createElement在导入的 HTML 文档中使用该方法(使用<link rel="import" href="...">),则在将图像附加到主文档的 DOM 之前,它实际上不会加载。有关更多详细信息,请参阅此 SO 问题/答案