开发者

Speed up JavaScript/jQuery function

开发者 https://www.devze.com 2023-02-18 14:31 出处:网络
I know that you can cache selectors in jquery/javascript by using “var = $xxx”. I am already doing this with all selectors that will be used more than once…

I know that you can cache selectors in jquery/javascript by using “var = $xxx”. I am already doing this with all selectors that will be used more than once…

Problem: The javascript animation is slow the first time the visitor activates the function by clicking. Next time they click it works without any hesitation.

Since I don’t know much about JavaScript I wonder if this is because of A or B below:

A: This is because the browser caches the se开发者_如何转开发lector only when the visitor has “clicked.

B: This is because the browser remembers the function/animation.

Question if A is true:

Is there a way to cache all selectors before the click functions?

Is there a way to make the browser remember the cached selectors until next time they visit the site?

Question if B is true:

Can I somehow cache the functions in JavaScript?

Or can I show how run all the functions when visitors arrive (for example first pop-up a loading div with z-index 10000 and run all functions behind it).

Here’s some example code:

$(document).ready(function(){

var $selector1 = $('#div1'),
$selector2 = $('#div2');

$selector1.click(function(){
$selector2.animate({height:'toggle'},350)
});

});

Sorry for my bad English.


Hopefully the comments answered your questions about caching in jQuery. As they said, your code seems good, so its probably an issue with the browser.

If you want to display a loading image while your page loads, you can add an loading image at the beginning of your page:

<div id="loader">
<img src="loader.gif" alt="Loading..." />
</div>

Then style it using CSS using something like:

#loader {
   z-index: 100;
   position: fixed;
   top: 50%;
   left: 50%;
   margin-left: -10px; //(or half the width of your loader image)
}

And then add the jQuery function to hide it after your page completes loading:

jQuery(window).load(function() {
   jQuery('#loader').hide();
});
0

精彩评论

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