Saturday, May 11, 2024
 Popular · Latest · Hot · Upcoming
63
rated 0 times [  69] [ 6]  / answers: 1 / hits: 123634  / 14 Years ago, fri, june 18, 2010, 12:00:00

Using Javascript I need to find the best way to add a iframe element that is:




  1. Completely hidden from the user.

  2. Created after the page has fully loaded. i.e. Should be completely unobtrusive to the user and not affect loading of images and other scripts etc, in any way.


More From » javascript

 Answers
10

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>



[#96457] Tuesday, June 15, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
harleyaleenag

Total Points: 678
Total Questions: 121
Total Answers: 105

Location: Papua New Guinea
Member since Thu, Jul 9, 2020
4 Years ago
harleyaleenag questions
Thu, May 5, 22, 00:00, 2 Years ago
Wed, Aug 19, 20, 00:00, 4 Years ago
;