How to make JavaScript execute after page load?

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

I\'m executing an external script, using a

24条回答
  •  不知归路
    2020-11-21 06:18

    JavaScript

    document.addEventListener('readystatechange', event => { 
    
        // When HTML/DOM elements are ready:
        if (event.target.readyState === "interactive") {   //does same as:  ..addEventListener("DOMContentLoaded"..
            alert("hi 1");
        }
    
        // When window loaded ( external resources are loaded too- `css`,`src`, etc...) 
        if (event.target.readyState === "complete") {
            alert("hi 2");
        }
    });
    

    same for jQuery:

    $(document).ready(function() {   //same as: $(function() { 
         alert("hi 1");
    });
    
    $(window).load(function() {
         alert("hi 2");
    });
    





    NOTE: - Don't use the below markup ( because it overwrites other same-kind declarations ) :

    document.onreadystatechange = ...
    

提交回复
热议问题