Home > Mobile >  Initialize a variable with a DOM element: is the "window.onload" best for it?
Initialize a variable with a DOM element: is the "window.onload" best for it?

Time:09-18

What's, or where is, the safet way to initialize a variable that points to a DOM element, let's say, a div or image?

let myImg;

window.onload (e) => {
  myImg = document.getElementById("my_img_1");
}

function doSomething(a, b, c) {
  //using myImg
}

Are there any issues with this code? Is this a proper way to initialize a DOM variable?

CodePudding user response:

The load event (what you're currently using) usually isn't a great choice because it happens really late, waiting until all resources (including images, etc.) are loaded. Sometimes you want that, but not often.

You have lots of options. Here's a list in my personal order of preference:

  1. Use type="module" on your script tag so your JavaScript code is a module, not a global script. Modules (both inline and via src) are automatically deferred (see the next item). (They also have other benefits: the code in them isn't at global scope, so they're nicely contained; they're automatically in strict mode; they can load other modules via import.) This works in all modern browsers (so, not with IE11).
  2. Use the defer attribute on your script tag. That tells the browser to download and parse the code, but not to run it until it's done parsing the HTML. Only works with src, though, not inline. This works in all modern browsers and also IE10 .
  3. Put the script at the end of the document, just prior to the closing </body> tag. It won't be run until all the HTML above it has been parsed and put in the DOM. This has always worked.
  4. Use the DOMContentLoaded event. This works in anything even vaguely modern, including IE9 .
  5. Use the load event (what you're currently using; just including it on the list for completeness). This has worked basically forever.

So for example:

<script type="module" src="your-code.js"></script>

your-code.js:

const myImg = document.getElementById("my_img_1");

function doSomething(a, b, c) {
    //using myImg
}

Inline example just to demonstrate the deferring:

Note that the script is above the img, but it still works — because the script execution is deferred.

  • Related