Using Javascript I need to find the best way to add a iframe element that is:
- Completely hidden from the user.
- 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.
You can add a hidden
iframelike this: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: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: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).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).