In many cases, we may not want a webpage to immediately load all <iframe> elements upon initial page load. This approach improves page load speed and enhances user experience. For example, if a page contains videos or other heavy content, we can optimize performance by loading these elements only when the user needs them.
One approach to achieve this is by dynamically creating <iframe> elements when clicking a button. Below are the specific implementation steps and example code:
Steps:
-
Create a button: Users click this button to load the
<iframe>. -
Use JavaScript to listen for button click events: When the button is clicked, execute a function that creates and inserts the
<iframe>. -
Dynamically insert
<iframe>: Inside the function, create a new<iframe>element, set itssrcattribute to the required URL, and insert it into the appropriate position in the DOM.
Example Code:
HTML part:
html<button id="loadIframe">Load video</button> <div id="iframeContainer"></div>
JavaScript part:
javascriptdocument.getElementById('loadIframe').addEventListener('click', function() { var iframe = document.createElement('iframe'); iframe.src = "https://www.example.com"; // Target URL for the iframe iframe.width = "560"; iframe.height = "315"; iframe.frameBorder = "0"; iframe.allow = "accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"; iframe.allowFullscreen = true; document.getElementById('iframeContainer').appendChild(iframe); });
Explanation:
-
Button (
<button>): Users click this button to trigger the loading of the<iframe>. -
Event listener: When the button is clicked, the listener triggers a function that creates the
<iframe>and sets necessary attributes (such assrc,width,height, etc.). -
Dynamic creation and insertion of
<iframe>: Upon clicking the button, JavaScript dynamically creates the<iframe>and inserts it into the page's#iframeContainercontainer.
This approach significantly reduces network requests and loading time during the initial page load, as the content within the <iframe> is only loaded and rendered when the user actually needs it. It is particularly useful for pages containing multiple heavy embedded content (such as videos, maps, etc.).