0

Say if I want to execute some code once the page is loaded. Is it more recommended to use the load event listener, like this:

window.addEventListener("load", function() {
    // example code
    for (var x = 0; x < l; x++) {
        console.log("yo");
    }
});

or can I just write what I want outside of any scope:

// example code
for (var x = 0; x < l; x++) {
    console.log("yo");
}

I mean, either one is gonna get executed once the page loads right? Does it have to do with, in the second case, wanting to access elements that haven't yet been loaded when the script does?

Thanks in advance.

  • If you don't need access to anything on the page, then there's not much point waiting for the page to load, it just adds extra code for no reason, I think – CertainPerformance Apr 14 '19 at 23:52
  • window.load is triggered when all content (including images, script files, CSS files, etc.) of the page is loaded. So if your code has nothing to do with one of these you could just execute it as you wish. – mchts Apr 14 '19 at 23:58
  • You use plain javascript or Jquery also? check this out - https://stackoverflow.com/questions/3698200/window-onload-vs-document-ready – Edgars Aivars Apr 14 '19 at 23:58
  • @CertainPerformance Hm. What if the last thing that I declare in the HTML file is the script. That means everything would've already been loaded and I wouldn't need the listener, right? – patoscript Apr 15 '19 at 00:00
  • That's right. (though I prefer putting the ` – CertainPerformance Apr 15 '19 at 00:02
  • Yeah I agree. And I was not aware of this ```defer``` tag. It's gonna be useful. Thank you everyone - my question has been answered and I will take a deeper look at your suggestions. – patoscript Apr 15 '19 at 00:12

0 Answers0