managing document.ready event(s) on a large-scale website

后端 未结 9 1607
予麋鹿
予麋鹿 2021-01-30 10:51

NOTE: I have now created a jQuery plugin which is my attempt of a solution to this issue. I am sure that it could be improved and i\'ve probably overlooked lots of use c

9条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-30 11:31

    Firstly, if you're using jQuery, document.getElementsByTagName isn't really necessary, you can just use $("tagname"). Have a look at the jQuery Selectors documentation for even more magic!

    Your work-in-progress solution is the way I would go about it, but you don't need to go to the trouble of defining extra functions, getting bodyClasses, running a loop, or any of that jazz... why not just use jQuery's .hasClass() function?

    $(function() {
        if($("body").hasClass("article")) {
            alert("some article specific code");
        }
        if($("body").hasClass("landingPage")) {
            alert("some landing specific code");
        }
    });
    

    Bam. All you need. If you want to be even more efficient, you can reuse one body query:

    $(function() {
        var body = $("body");
        if(body.hasClass("article")) {
            alert("some article specific code");
        }
        if(body.hasClass("landingPage")) {
            alert("some landing specific code");
        }
    });
    

    Here it is on jsfiddle: http://jsfiddle.net/W8nx8/6/

提交回复
热议问题