When to use “window.onload”?
问题 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? For example, if I want to have a pop-up, should I write (directly inside the <script> tag): alert("hello!"); Or: window.onload = function() { alert("hello!"); } Both appear to run just after the page is loaded. What is the the difference? 回答1: window.onload just runs when the browser gets to it. window.addEventListener waits for the window to be loaded before running