Javascript: add iframe element after page has loaded

You can add a hidden iframe like this:

const iframe = document.createElement("iframe");
iframe.style.display = "none";
iframe.src = /* your URL here */;
document.body.appendChild(iframe);

If you need to do that on page load, you can:

  • Use type="module" on your script tag to make it a module (in environments that support modules; basically everywhere now). Modules are really useful for encapsulation, and also get deferred (not executed until the HTML is fully parsed and the DOM populated with the results). Using type="module" defers execution even with inline scripts. Example:

    <script type="module">
    const iframe = document.createElement("iframe");
    iframe.style.display = "none";
    iframe.src = /* your URL here */;
    document.body.appendChild(iframe);
    </script>
    
  • Use defer on your script tag (in environments that don’t yet support modules). defer scripts don’t run until the HTML is parsed and the DOM populated with the results. Unfortunately, though, defer only works with src scripts, not inline scripts. So you could put the code above in a .js file and use:

    <script defer src="./yourfile.js"></script>
    
  • Put your script at the very end of the body, just before the closing </body> element (in environments that don’t support type="module" or defer, but there basically aren’t any left, even IE11 supported defer).

    <script>
    const iframe = document.createElement("iframe");
    iframe.style.display = "none";
    iframe.src = /* your URL here */;
    document.body.appendChild(iframe);
    </script>
    </body><!-- <========= Notice this is at the end of the body tag -->
    
  • Hook it up via the window load event, but I don’t recommend it; the window load event happens quite late in the page load process (waiting for all images to load, for instance).

    <!-- NOT RECOMMENDED -->
    <script>
    window.addEventListener(function() {
         const iframe = document.createElement("iframe");
         iframe.style.display = "none";
         iframe.src = /* your URL here */;
         document.body.appendChild(iframe);
    });
    </script>
    

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)