In JavaScript, when I want to run a script once when the page has loaded, should I use window.onload or just write the script?
window.onload
For example, if I want to
You have three alternatives:
Directly inside the script tag runs it as soon as it is parsed.
Inside document.addEventListener( "DOMContentLoaded", function(){}); will run it once the DOM is ready.
document.addEventListener( "DOMContentLoaded", function(){});
Inside window.onload function(){}) will run as soon as all page resources are loaded.
window.onload function(){})