How to make JavaScript execute after page load?

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

I\'m executing an external script, using a

24条回答
  •  Happy的楠姐
    2020-11-21 06:10

    There is a very good documentation on How to detect if document has loaded using Javascript or Jquery.

    Using the native Javascript this can be achieved

    if (document.readyState === "complete") {
     init();
     }
    

    This can also be done inside the interval

    var interval = setInterval(function() {
        if(document.readyState === 'complete') {
            clearInterval(interval);
            init();
        }    
    }, 100);
    

    Eg By Mozilla

    switch (document.readyState) {
      case "loading":
        // The document is still loading.
        break;
      case "interactive":
        // The document has finished loading. We can now access the DOM elements.
        var span = document.createElement("span");
        span.textContent = "A  element.";
        document.body.appendChild(span);
        break;
      case "complete":
        // The page is fully loaded.
        console.log("Page is loaded completely");
        break;
    }
    

    Using Jquery To check only if DOM is ready

    // A $( document ).ready() block.
    $( document ).ready(function() {
        console.log( "ready!" );
    });
    

    To check if all resources are loaded use window.load

     $( window ).load(function() {
            console.log( "window loaded" );
        });
    

提交回复
热议问题