Speed ​​up JavaScript / jQuery Function

I know that you can cache selectors in jquery / javascript using "var = $ xxx". I already do this with all selectors that will be used more than once ...

Problem: Javascript animation is slow when a visitor activates a function with a click of a button. The next time they click, it works without any hesitation.

Since I'm not very good at JavaScript, I wonder if this is related to A or B:

A: This is due to the fact that the browser caches the selector only when the visitor "clicked".

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

The question is if A is true:

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

Is there a way to make the browser remember the cache selector before the next visit to the site?

The question is if the value of B is true:

Is there any way to cache functions in JavaScript?

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

Here is a sample code:

$(document).ready(function(){

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

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

});

Sorry for my bad english.

+3
source share
1 answer

We hope that the comments answered your questions about caching in jQuery. As they said, your code seems to be good, so its probably a browser issue.

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

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

CSS, - :

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

jQuery, :

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

All Articles