What's making every embedded object contentDocument “unique” even having two (or more) istances of the same object source?

坚强是说给别人听的谎言 提交于 2019-12-25 00:22:50

问题


I put several instances of the same object in an HTML page. In my case I'm dealing with SVG and I have something like this:

<object data="same.svg" type="image/svg+xml"></object>
<object data="same.svg" type="image/svg+xml"></object>
<object data="same.svg" type="image/svg+xml"></object>

Being used exactly the same SVG source for every object, I was thinking the contentDocument to be the same when compared BUT then I put the following code inside the source SVG:

<script type="text/javascript"><![CDATA[
  async function compare_test(){
    await (new Promise(resolve => setTimeout(resolve,2000)));
    let objects = window.parent.document.getElementsByTagName("object");
    for (let i=objects.length-1; i>=0; i--){
      if (objects[i].contentDocument == this.document){
        console.log("matching object found:");
        console.log(objects[i]);
        break;
      }
    }
  }
]]></script>

To my amazement I noticed things work well and the object matched seems always be the correct one! I'm wondering how is it possible? So... is there some browsers mechanism that makes every content document of the objects in the page "unique"? What is it?


回答1:


This isn't a specific browser mechanic. It is just that the browser is actually simpler than you think.

The fact that the three embedded "documents" come from the same file is irrelevant. It is still three different objects, because you explicitly specified three object tags. The three SVG instances are each interpreted (executed/rendered) independently. Maybe some script inside the SVG is generating some random shapes? Then you'll have three different images. You need to realize that a "document" isn't just the file from which it comes from. A document holds the entire state of execution of the file (and eventually its inner scripts). So it has to be like that.

Of course, the browser certainly fetches "same.svg" only once, due to caching. But still, it is executed three times, and therefore, there needs to be three different content documents (each with its own specific state).

So there can be no ambiguity with the method you're using.



来源:https://stackoverflow.com/questions/54771696/whats-making-every-embedded-object-contentdocument-unique-even-having-two-or

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!