乐闻世界logo
搜索文章和话题

How do I make < iframes > load only on a button click?

1个答案

1

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:

  1. Create a button: Users click this button to load the <iframe>.

  2. Use JavaScript to listen for button click events: When the button is clicked, execute a function that creates and inserts the <iframe>.

  3. Dynamically insert <iframe>: Inside the function, create a new <iframe> element, set its src attribute 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:

javascript
document.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 as src, 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 #iframeContainer container.

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.).

2024年8月13日 10:35 回复

你的答案