How to make JavaScript execute after page load?

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

I\'m executing an external script, using a

24条回答
  •  离开以前
    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 (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 (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

    
    
    
      
    
    
    
      

提交回复
热议问题