jquerydomwindow-load

What's the difference between `$(window).load(function(){})` and `$(function(){})`


I was using $(window).load(function(){}); for my projects until somewhere I saw that somebody said we could just use $(function(){}); and they would perform identically.
But now that I have more experience I have noticed that they are not identical. I noticed that the first piece kicks in a little bit after the second piece of code.
I just want to know what's the difference?


Solution

  • $(document).ready(function(){})
    

    will wait till the document is loaded(DOM tree is loaded) and not till the entire window is loaded. for example It will not wait for the images,css or javascript to be fully loaded . Once the DOM is loaded with all the HTML components and event handlers the document is ready to be processed and then the $(document).ready() will complete

    $(window).load(function(){});

    This waits for the entire window to be loaded. When the entire page is loaded then only the $(window).load() is completed. Hence obviously $(document).ready(function(){}) finishes before $(window).load() because populating the components(like images,css) takes more time then just loading the DOM tree.

    So $(function(){}); cannot be used as a replacement for $(window).load(function(){});