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 yourscripttag 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). Usingtype="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
deferon yourscripttag (in environments that don’t yet support modules).deferscripts don’t run until the HTML is parsed and the DOM populated with the results. Unfortunately, though,deferonly works withsrcscripts, not inline scripts. So you could put the code above in a.jsfile and use:<script defer src="./yourfile.js"></script> -
Put your
scriptat the very end of the body, just before the closing</body>element (in environments that don’t supporttype="module"ordefer, but there basically aren’t any left, even IE11 supporteddefer).<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
windowloadevent, but I don’t recommend it; thewindowloadevent 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>