window page load event

When we didn't learn BOM before, the order of writing HTML and Script was to write HTML first and then write Script. The purpose is to let HTML load first before executing the subsequent interactive effects, but after learning BOM, we can implement Script tags let it go


window.addEventListener('load',function(}) :

This method can make the content of the document fully loaded and then execute the content of JS, including pictures, flash, css, script files, etc. ( if window.οnlοad=function(){} is used, the same element can only be used by Register once, and the last time will prevail. You can register multiple times using this listener function to register events) , the Script tag can be placed in front of HTML, in the head, or outside, the following is the use of After this method, the Script tag is placed in the upper part of the HTML tag

  <script>
        window.addEventListener('load',function(){
             var ele=document.querySelector('button');
        ele.addEventListener('click',function(){
            alert('我弹出啦');
          })
    })
     </script>
    <button>按钮</button>


document.addEventListener('DOMContentLoaded',function(}) :

The difference between this method and the above is that this event can execute the interactive content of JS only when the DOM is loaded, excluding pictures, css, flash, script files, etc. If there are many pictures on a page, using the onload event will cost a lot of money. a lot of time, then using this event to register will greatly reduce the time users spend waiting for the page

 <script>
        window.addEventListener('DOMContentLoaded',function(){
             var ele=document.querySelector('button');
        ele.addEventListener('click',function(){
            alert('我弹出啦');
          })
    })
     </script>
    <button>按钮</button>

Guess you like

Origin blog.csdn.net/weixin_52212950/article/details/123281036