Difference between DOMContentLoaded and load events

后端 未结 6 1956
执笔经年
执笔经年 2020-11-22 08:43

What is the difference between DOMContentLoaded and load events?

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 08:54

    Here's some code that works for us. We found MSIE to be hit and miss with DomContentLoaded, there appears to be some delay when no additional resources are cached (up to 300ms based on our console logging), and it triggers too fast when they are cached. So we resorted to a fallback for MISE. You also want to trigger the doStuff() function whether DomContentLoaded triggers before or after your external JS files.

    // detect MSIE 9,10,11, but not Edge
    ua=navigator.userAgent.toLowerCase();isIE=/msie/.test(ua);
    
    function doStuff(){
        //
    }
    if(isIE){
        // play it safe, very few users, exec ur JS when all resources are loaded
        window.onload=function(){doStuff();}
    } else {
        // add event listener to trigger your function when DOMContentLoaded
        if(document.readyState==='loading'){
            document.addEventListener('DOMContentLoaded',doStuff);
        } else {
            // DOMContentLoaded already loaded, so better trigger your function
            doStuff();
        }
    }
    

提交回复
热议问题