jQuery - What are differences between $(document).ready and $(window).load?

前端 未结 8 2192
旧巷少年郎
旧巷少年郎 2020-11-22 02:45

What are differences between

$(document).ready(function(){
 //my code here
});

and

$(window).load(function(){
  //my code h         


        
相关标签:
8条回答
  • 2020-11-22 03:42

    document.ready is a jQuery event, it runs when the DOM is ready, e.g. all elements are there to be found/used, but not necessarily all the content.
    window.onload fires later (or at the same time in the worst/failing cases) when images and such are loaded. So, if you're using image dimensions for example, you often want to use this instead.

    Also read a related question:
    Difference between $(window).load() and $(document).ready() functions

    0 讨论(0)
  • 2020-11-22 03:44

    $(window).load is an event that fires when the DOM and all the content (everything) on the page is fully loaded like CSS, images and frames. One best example is if we want to get the actual image size or to get the details of anything we use it.

    $(document).ready() indicates that code in it need to be executed once the DOM got loaded and ready to be manipulated by script. It won't wait for the images to load for executing the jQuery script.

    <script type = "text/javascript">
        //$(window).load was deprecated in 1.8, and removed in jquery 3.0
        // $(window).load(function() {
        //     alert("$(window).load fired");
        // });
    
        $(document).ready(function() {
            alert("$(document).ready fired");
        });
    </script>
    

    $(window).load fired after the $(document).ready().

    $(document).ready(function(){
    
    }) 
    //and 
    $(function(){
    
    }); 
    //and
    jQuery(document).ready(function(){
    
    });
    

    Above 3 are same, $ is the alias name of jQuery, you may face conflict if any other JavaScript Frameworks uses the same dollar symbol $. If u face conflict jQuery team provide a solution no-conflict read more.

    $(window).load was deprecated in 1.8, and removed in jquery 3.0

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