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) {
}
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:
- 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).
- 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 .
- 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.
- Use the
DOMContentLoaded
event. This works in anything even vaguely modern, including IE9 .
- 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) {
}
Inline example just to demonstrate the deferring:
<script type="module">
const myImg = document.getElementById("my_img_1");
function doSomething(a, b, c) {
myImg.style.border = "2px solid yellow";
}
doSomething();
</script>
<img id="my_img_1" src="data:image/png;base64,/9j/4AAQSkZJRgABAQEASABIAAD/2wBDABQODxIPDRQSEBIXFRQYHjIhHhwcHj0sLiQySUBMS0dA
RkVQWnNiUFVtVkVGZIhlbXd7gYKBTmCNl4x9lnN gXz/2wBDARUXFx4aHjshITt8U0ZTfHx8fHx8
fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHz/wgARCACAAIADAREA
AhEBAxEB/8QAGQABAAMBAQAAAAAAAAAAAAAAAAMEBQEC/8QAGQEBAAMBAQAAAAAAAAAAAAAAAAEC
AwQ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Ie5UC/yYnz/dA8AsgepjqWoAQRuJnxC5LKaWKsY1/r2o2EsHj1fD
Q1oXdT wfJ9TLCkRsnhDOGksv23WjgAgDgDIAariucOlJx0MHIC8SK5rK3pjrjNxudMngkFEPNfZ
8qhAyXlj7z4qgg18n/aATY0TmE8XemROmKvlgU7wxxZShCmNnvUIcSJs5O/FGGIObB80AALBBxX0
tsao/wDKbIiYUiV4zKPOQRptCE9Td9 Mm5w64qVmWcNj h429wPZflcDh7f1xv7g HBFBBgz66VG
8JRBnxkGyKWYCmwtQAsvWmjA3I9/44qEzHRk aEKXDuVIZhYUwNOkSgEQ NHAbYODLV85by2MW9a
FXOnXFS0QxuYf1eMSph5L7HnV3Mg5YoqZCE5VNC59zDQdASJnwgEFekgotzYwdaAAAgKjdBKHod6
iW0FMuXv4GCKWMLqeetRxlI03G5oaqrgg22ejhogg9FoCSInKhZAbrRKbaXnehd4a4dN2o g9Xek
ZsaG7tRLarFy6T0NPDDvsJUA1vps0dK21LSJqJI00qjuk7VNnrISpMPOEtMgpz27UAAABoFMoGwa
ryKKChY35H7oMAoBg8WpABFahcOA6UnwRZQY7alBeWl1SVIZoBljEy9qn62il6UEQtQvv igyCgA
sfhKhLkgeZekVRdAAPag0KHJnzVgbIm/NNSntAeleUfif83/2Q==">
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
Note that the script
is above the img
, but it still works — because the script execution is deferred.