Why are iframes so slow?

2020-05-17 04:32发布

问题:

I have little bit longer question for you - but hope answer will be very simple :)

Let's say I have very simple page with link and iframe (just for simple example).

<body>
    <a href="test.html" target="mframe">open link></a>
    <iframe name="mframe" [params] />
</body>

So when you click on the link it will load test.html in the frame.

Now I will change the iframe with div and ajax call.

<body>
    <a href="doAjaxCall('test.html')">open link</a>
    <div id="main-content"></div>
</body>

The doAjaxCall will simply use GET ajax requset to get whole response, parse it (using JavaScript) and grab content in <body> tag and put it into main-content.innerHTML.

test.html contains a lot of html, also css styles (but the same as are on parent page - so I don't need them when I'm using ajax solution).

Question:

Why is this ajax solution SO faster? I'm still downloading the same amount of data (downloading whole test.html).

Why is the iframe solution so slow? Is it because of browser have to parse all possible styles again? Or is there any other overhead of iframes?

回答1:

You are pretty much on the right track. iframes are going to be slower because there is an additional overhead for the browser (rendering it, maintaining it's instance and references to it).

The ajax call is going to be a bit faster because you get the data in and you then inject it, or do whatever you want with it. The iframe will need to build an entirely new "page" in the browsers memory, and then place it in the page.



回答2:

Steve Souders has a post Using Iframes Sparingly on his High Performance Web Sites blog that may provide some more insight.



回答3:

Although the browsers have improved since 2009, the fact that the browser needs to hit additional servers (assuming the iframes are for thrid-party content), or hit the local server again (assuming the iframes are for local content), this would still impact page performance. In general, additional HTTP requests will always have an impact on a page's performance. If it's possible to build the iframe after the page is loaded and than render the iframe's content, this would improve the initial page load. However, I think this would impact the pages performance while the iframe loads the additional content.