How to optimize jQuery code
By FoxLearn 7/3/2024 2:25:46 AM 183
Here are some tips to optimize your jQuery script.
1. Minimize DOM Selections
You should cache jQuery selectors in variables if you're using them multiple times, rather than querying the DOM repeatedly.
// Bad $('.myClass').css('color', 'red'); $('.myClass').addClass('active'); // You should modify your code var $myElements = $('.myClass'); $myElements.css('color', 'red'); $myElements.addClass('active');
2. Chain your jQuery functions most as possible
Chain jQuery methods where possible to reduce overhead from multiple function calls.
// Bad $("#myElement").addClass('active'); $("#myElement").css('color', 'red'); // Chained method calls $('#myElement').addClass('active').css('color', 'red');
3. Minify your javascript files and combine them in 1 file
It helps you speed up script loading, so you spend more milliseconds for the script to be executed.
4. Event Delegation
Use event delegation with .on()
for dynamically created elements or for better performance with large numbers of elements.
// Bad $('.myClass').click(function() { // Event handler }); // Good $(document).on('click', '.myClass', function() { // Event handler });
5. Use the native for method instead $.each
var array = []; for (var i=0; i<1000; i++) { array[i] = i; }
6. Use a limited area to search
When using a class selector, you should give a limited area to search for it.
// bad $(".myClass"); // Good $(".myClass","#myClass-container");
7 Use Native JavaScript
Where applicable, use native JavaScript methods (querySelector
, addEventListener
) instead of jQuery for better performance.
8. Use jQuery Slim Build
Consider using the slim version of jQuery (jquery.slim.min.js
) which excludes Ajax and effects modules if you do not need them, reducing file size.
<script src="https://code.jquery.com/jquery-3.6.0.slim.min.js"></script>
9. Lazy Loading
Load jQuery asynchronously or at the bottom of your HTML to prevent blocking rendering.
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsVQUB8qq/dW+8E3ajXo4FjBSaqz3X8GY5lDDvD9Wm" crossorigin="anonymous" defer></script>
Through this post, i hope so you can optimize your jQuery code for better performance, maintainability, and efficiency.