开发者

Only perform jquery effects/operations on certain pages

Up until now i've been dropping all my jquery code right inside the document.ready function. I'm thinking that for certain situations this isnt the best way to go.

for example: If i want an animation to perform when a certain page loads what is the best way to go about that.

$(document).ready(function() {
    $("#element_1").fadeIn();
    $("#element_2").delay('100').fadeIn();
    $("#element_3").delay('200').fadeIn();
});

If this is right inside of document.ready then every time ANY page loads 开发者_运维技巧it's going to check each line and look for that element. What is the best way to tell jquery to only perform a chunk of code on a certain page to avoid this issue.


by checking if elememt exist on the page before execute animation

if ($("#element-1").length) { 
   $("#element-1").fadeIn();
}

and so on with other elements #element_2 and #element_3


to @numediaweb:

current jQuery is() implementation is like below

is: function( selector ) {
  return !!selector && jQuery.filter( selector, this ).length > 0;
 },

so, it can be smarter to use is() but it is faster to use just length and even faster to sue document.getElementById().length


Only include the code you want to be executed when the DOM is ready for that particular page. $(document).ready(... does not mean that you should have the same chunk of code run on each page. That would necessitate performing various checks in order to know what needs to be executed.

I'm sure that you will have some common functionality that you would want to execute on each page, as well as some page-specific functionality. If that is the case, then you could put the common functionality into a single function, and call it from the $(document).ready(... such that the only remaining code is specific to that particular page. For example:

function common() {
    alert('hello');
}

$(document).ready(function() {
    common();
    // do some page-specific stuff
});

I disagree with performing various checks on every single page so the code knows where we're at. It seems cumbersome and totally avoidable, for instance:

function doAnimation() {
    $("#element_1").fadeIn();
    $("#element_2").delay('100').fadeIn();
    $("#element_3").delay('200').fadeIn();
}

$(document).ready(function() {
    if(window.location.href == 'http://example.com/foo') {
        doAnimation();
    }
    if(this page has blah) {
        doBlah();
    }
});

Ideally, what it should be is:

$(document).ready(function() {
    // do stuff for foo.php
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜