开发者

javascript (jquery) - codes should be on -> onload or document.ready or pageLoad()?

开发者 https://www.devze.com 2023-02-20 11:04 出处:网络
plz see the below codes : 1 2 3 +1+ $(document).ready(function() { //Do Some Stuff Here alert(\"document.ready\");

plz see the below codes : 1 2 3

+1+

$(document).ready(function() 
             {
                    //Do Some Stuff Here
                    alert("document.ready");
             });

+2+

        //onload = onloadOfDocument;

    //or

        window.onload = onloadOfDocument;

        function onloadOfDocument() 
        {
                //Do Some Stuff Here
            alert("onloadOfDocument");
        }

+3+

        function pageLoad()
        {
                //Do Some Stuff Here
            alert("pageLoadFromJS");
        }

the javascript or jquery codes should be on 开发者_StackOverflow社区which number of upper codes (which better)?

i mean in which part , dom is completely loaded and so we do not have any problem for recognizing elements inside it?

i just know alert("document.ready"); is fired before onload - but somebody told me document.ready is better! WHY?

and what about pageLoad() function ? (is it a pre defined function or it's just a function with no meaning)?

++thanks for this helpful and comfortable area for A & Q++

++STACKOVERFLOW IS THE BEST++


1) jQuery's .ready handler loads when the DOM is ready. This means it will fire before some other things are loaded like images.

Generally when running javascript you only care about the DOM being ready.

2) runs when the entire document is loaded. This is ok if you don't have jQuery on the page and loading of images is not going to slow you down noticeably.

3) This is just a function declaration. It is not in build. The browser does not run it for you.

The entire point of using $(document).ready(f); is to ensure that you do not manipulate the DOM with javascript before it is ready. If your very unlucky you can corrupt the DOM. If your less unlucky your selectors do not work as expected because the elements are not in the DOM when you run the javascript code.


  1. Let jQuery do all the work of determining when the page is ready.
0

精彩评论

暂无评论...
验证码 换一张
取 消