iframe
iframe technology is not obsolete and still has its place, such as in web advertising, Chrome extensions, and other applications. Users may not notice the difference in UI experience, but they are actually interacting with two different site services. Here’s a summary of iframe considerations.
If the iframe contains a same-site page, it shares the parent page’s rendering process. Chrome does not start a new process. If it’s a different site, a new rendering process is started.
- Sharing the same rendering process means that if the child page enters an infinite loop, the parent page will be in a waiting state and become unresponsive.
- It’s important to understand two concepts: same-origin means
protocol; domain; port are identical
, while same-site meansroot domain is identical
- For example, alan.local page iframe loads a.alan.local page
iframe resource loading itself does not block the parent page’s HTML parsing and execution, but the parent page’s onload event executes after the child page’s onload
- Need to understand the page lifecycle events:
- window.onload: The browser has not only loaded HTML but also all external resources: images, styles, etc.
- DOMContentLoaded: The browser has fully loaded HTML and built the DOM tree, but external resources like images and stylesheets may not have finished loading.
- beforeunload/unload: Page destruction and leaving
- Need to understand the page lifecycle events:
As a cross-origin resource access solution, iframe communication between pages can be categorized into the following two scenarios:
Same-site
- Both sites set
document.domain = 'alan-test.local';
which allows JavaScript to manipulate page elements, such as child pagewindow.parent.document.getElementById('saveSession')
, and parent page manipulating child page viawindow.frames['frameId'].document
- Both sites set
Different sites
Use CDM (cross document messaging) for communication
window.addEventListener("message", (event) => { if (event.origin !== "http://example.org:8080") return; // ... }, false); targetWindow.postMessage(message, targetOrigin, [transfer]);
Final Thoughts
iframe remains a valuable technology for specific use cases where embedding external content or creating isolated environments is necessary. Understanding the rendering process sharing, resource loading behavior, and communication mechanisms between same-site and cross-site iframes is crucial for effective implementation. While modern web development often favors alternative approaches for security and performance reasons, iframes continue to serve important roles in web advertising, browser extensions, and legacy system integrations.