How to make JavaScript execute after page load?

前端 未结 24 2350
孤城傲影
孤城傲影 2020-11-21 05:55

I\'m executing an external script, using a

24条回答
  •  花落未央
    2020-11-21 06:22

    Keep in mind that loading the page has more than one stage. Btw, this is pure JavaScript

    "DOMContentLoaded"

    This event is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. At this stage you could programmatically optimize loading of images and css based on user device or bandwidth speed.

    Executes after DOM is loaded (before img and css):

    document.addEventListener("DOMContentLoaded", function(){
        //....
    });
    

    Note: Synchronous JavaScript pauses parsing of the DOM. If you want the DOM to get parsed as fast as possible after the user requested the page, you could turn your JavaScript asynchronous and optimize loading of stylesheets

    "load"

    A very different event, load, should only be used to detect a fully-loaded page. It is an incredibly popular mistake to use load where DOMContentLoaded would be much more appropriate, so be cautious.

    Exectues after everything is loaded and parsed:

    window.addEventListener("load", function(){
        // ....
    });
    

    MDN Resources:

    https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded https://developer.mozilla.org/en-US/docs/Web/Events/load

    MDN list of all events:

    https://developer.mozilla.org/en-US/docs/Web/Events

提交回复
热议问题