简体   繁体   中英

When does a web browser request the src content of a dynamically created iframe?

Let's say I dynamically create an iframe node by using js, then set the src attribute (1) and finally append the node to the DOM (2).

When is the src content requested by the browser? After (1)? After (2)? Or is it unpredictable? Does it depend on the browser?

The specification states:

When an iframe element is first inserted into a document , the user agent must create a nested browsing context , and then process the iframe attributes for the first time.


Using the following snippet and a local server, I've tested the behaviour in many browsers.

 var f = document.createElement('iframe'); f.src = '/?'; 

The resource is never fetched (I've only shown the lowest and highest tested browser version):

  • IE 6 - 9
  • FF 3.6 - 12.0
  • Chrome 1 - 18
  • Opera 10.00 - 12.00
  • Safari 4.0 - 5.1.5

So, it the request is only sent once the frame is appended to the document.

After (2). Before that it's just JS. The browser won't act upon it until it's attached to the DOM.

Well, I'm not going to test every browser for you but I would always expect elements with src and href attributes that link to or load contents of some kind to always load after they're actually appended since when/where an iframe or a js file falls in the document hits on a ton of security and general implementation concerns. It would be critical fail on a browser vendor's part to do it any other way and I can see for a fact that chrome does it that way with a little experimentation.

The only exception I can think of is images which can be loaded before insertion.

In my experience it has always been when the node is added to the DOM. You can load up Firebug, or some other dev console, and see when this occurs. Throw in a couple alerts to be sure about the timing like this:

<script type="text/javascript">
    ifrm = document.createElement("IFRAME"); 
    ifrm.setAttribute("src", "http://blah.com/");
    alert('SRC SET'); 
    ifrm.style.width = 640+"px"; 
    ifrm.style.height = 480+"px"; 
    document.body.appendChild(ifrm);
    alert('ADDED TO DOM');
</script>

Run something like that and watch the "Net" tab in Firebug to see when the page is requested. I believe it will only be requested after the appendChild is called.

After (2)!! take a look at this: http://jsfiddle.net/lbstr/td7DD/

Open up firebug or chrome's console and look at the net tab. You will see google loading. Then, comment out the third line and run it again. You won't see google loading.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM