How to execute code before window.load and after DOM has been loaded?

前端 未结 4 1851
鱼传尺愫
鱼传尺愫 2020-12-09 08:36

Here is the circumstance: I have 2 pages:

  • 1 x html page
  • 1 x external Javascript

Now in the html page, there will be internal Ja

4条回答
  •  北海茫月
    2020-12-09 09:39

    It is also possible to use the DOMContentLoaded event of the Window interface.

    addEventListener("DOMContentLoaded", function() {
        // Your code goes here
    });
    

    The above code is actually adding the event listener to the window object, though it's not qualified as window.addEventListener because the window object is also the global scope of JavaScript code in webpages.

    DOMContentLoaded happens before load, when images and other parts of the webpage aren't still fully loaded. However, all the elements added to the DOM within the initial call stack are guaranteed to be already added to their parents prior to this event.

提交回复
热议问题