How to make JavaScript execute after page load?

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

I\'m executing an external script, using a

相关标签:
24条回答
  • 2020-11-21 06:24
    $(window).on("load", function(){ ... });
    

    .ready() works best for me.

    $(document).ready(function(){ ... });
    

    .load() will work, but it won't wait till the page is loaded.

    jQuery(window).load(function () { ... });
    

    Doesn't work for me, breaks the next-to inline script. I am also using jQuery 3.2.1 along with some other jQuery forks.

    To hide my websites loading overlay, I use the following:

    <script>
    $(window).on("load", function(){
    $('.loading-page').delay(3000).fadeOut(250);
    });
    </script>
    
    0 讨论(0)
  • 2020-11-21 06:24

    Comparison

    In below snippet I collect choosen methods and show their sequence. Remarks

    • the document.onload (X) is not supported by any modern browser (event is never fired)
    • if you use <body onload="bodyOnLoad()"> (F) and at the same time window.onload (E) then only first one will be executed (because it override second one)
    • event handler given in <body onload="..."> (F) is wrapped by additional onload function
    • document.onreadystatechange (D) not override document .addEventListener('readystatechange'...) (C) probably cecasue onXYZevent-like methods are independent than addEventListener queues (which allows add multiple listeners). Probably nothing happens between execution this two handlers.
    • all scripts write their timestamp in console - but scripts which also have access to div write their timestamps also in body (click "Full Page" link after script execution to see it).
    • solutions readystatechange (C,D) are executed multiple times by browser but for different document states:
      • loading - the document is loading (no fired in snippet)
      • interactive - the document is parsed, fired before DOMContentLoaded
      • complete - the document and resources are loaded, fired before body/window onload

    <html>
    
    <head>
      <script>
        // solution A
        console.log(`[timestamp: ${Date.now()}] A: Head script`);
        
        // solution B
        document.addEventListener("DOMContentLoaded", () => {
          print(`[timestamp: ${Date.now()}] B: DOMContentLoaded`);
        });
    
        // solution C
        document.addEventListener('readystatechange', () => {
          print(`[timestamp: ${Date.now()}] C: ReadyState: ${document.readyState}`);
        });
       
        // solution D
        document.onreadystatechange = s=> {print(`[timestamp: ${Date.now()}] D: document.onreadystatechange ReadyState: ${document.readyState}`)};
        
        // solution E (never executed)
        window.onload = () => {
          print(`E: <body onload="..."> override this handler`);
        };
    
        // solution F
        function bodyOnLoad() {
          print(`[timestamp: ${Date.now()}] F: <body onload='...'>`);      
          infoAboutOnLoad(); // additional info
        }
        
        // solution X
        document.onload = () => {print(`document.onload is never fired`)};
    
    
    
        // HELPERS
    
        function print(txt) { 
          console.log(txt);
          if(mydiv) mydiv.innerHTML += txt.replace('<','&lt;').replace('>','&gt;') + '<br>';
        }
        
        function infoAboutOnLoad() {
          console.log("window.onload (after  override):", (''+document.body.onload).replace(/\s+/g,' '));
          console.log(`body.onload==window.onload --> ${document.body.onload==window.onload}`);
        }
                
        console.log("window.onload (before override):", (''+document.body.onload).replace(/\s+/g,' '));
    
      </script>
    </head>
    
    <body onload="bodyOnLoad()">
      <div id="mydiv"></div>
    
      <!-- this script must te at the bottom of <body> -->
      <script>
        // solution G
        print(`[timestamp: ${Date.now()}] G: <body> bottom script`);
      </script>
    </body>
    
    </html>

    0 讨论(0)
  • 2020-11-21 06:27

    If the scripts are loaded within the <head> of the document, then it's possible use the defer attribute in script tag.

    Example:

    <script src="demo_defer.js" defer></script>
    

    From https://developer.mozilla.org:

    defer

    This Boolean attribute is set to indicate to a browser that the script is meant to be executed after the document has been parsed, but before firing DOMContentLoaded.

    This attribute must not be used if the src attribute is absent (i.e. for inline scripts), in this case it would have no effect.

    To achieve a similar effect for dynamically inserted scripts use async=false instead. Scripts with the defer attribute will execute in the order in which they appear in the document.

    0 讨论(0)
  • 2020-11-21 06:27

    Use this code with jQuery library, this would work perfectly fine.

    $(window).bind("load", function() { 
    
      // your javascript event
    
    });
    
    0 讨论(0)
  • 2020-11-21 06:29

    You can put a "onload" attribute inside the body

    ...<body onload="myFunction()">...
    

    Or if you are using jQuery, you can do

    $(document).ready(function(){ /*code here*/ }) 
    
    or 
    
    $(window).load(function(){ /*code here*/ })
    

    I hope it answer your question.

    Note that the $(window).load will execute after the document is rendered on your page.

    0 讨论(0)
  • 2020-11-21 06:29

    Look at hooking document.onload or in jQuery $(document).load(...).

    0 讨论(0)
提交回复
热议问题