3 seconds. It sounds like a short amount of time but in relation to page speed, 3 seconds is all it takes for 53% of users to abandon a mobile site.1
As a developer, this is a nightmare!
The last thing you want is slow page speed. Not only does this drive users away from your site, but it will also affect your site’s SEO ranking. Google would not want to recommend your site to users if they will be frustrated by its slow load times.
Clearly, page speed is essential to consider when developing a site. So, how can we improve it? There are many factors that can affect page speed such as the number of assets, interactive elements, or unused code.
One major factor I’ll be focusing on today is the optimization of JavaScript code.
Inefficiently written JavaScript code can be time expensive and lead to poor site performance. The good news, this can be easily improved by following these 10 best practices for optimizing your JavaScript code.
10 Best JavaScript Practices
1. Cache your objects
There are many ways to access elements in the DOM using JavaScript code such as document.getElementById() or document.getElementsByClassName(). However, every time you request access to an element, your browser has to search through all of the elements on the page. This leads to poor page speed.
If we need to access an object more than once, it is important to cache the object. Caching an object means storing the object inside a defined variable. This variable can be used to reference the object as many times as it is needed, without repeatedly looping through all the elements to find it again.
Example:
2. Save variables at a local scope
The scope of a variable is where in the program that variable can be accessed. If a variable is declared inside a JavaScript function, the variable is local to that function. It cannot be used outside of that function. Therefore, the variable has a local scope. On the other hand, if a variable is declared outside a JavaScript function, it is accessible throughout the entire program. Therefore, the variable has a global scope.
JavaScript searches to see if a variable exists locally before it searches through the higher levels of scope. In other words, it takes your program less time to access local variables than global variables. As a result, you should avoid using global variables if it is not necessary and declare your variables at a local scope.
Example:
3. Avoid unnecessary variables2
Variables take up memory. Therefore, you do not want to assign a value to a variable if you do not plan to save its values.
Bad Example:
If you are never going to use the change value again, there is no reason to save it as a variable, and can simply just replace the code with this better example:
4. Reduce activity in loops2
With each iteration, a for loop executes the block of code inside of the loop as well as the for statement itself. So if there is code that does not need to be executed more than once, add it outside of the loop.
Example:
In the example above, the length property of the exampleArray has to be accessed with each iteration of the loop. However, this value never changes, so there is no keep reaccessing the same length property. To make the loop run faster, we can save the length value to a variable outside of the loop.
Better Example:
5. Use Switch/Case instead of If/Else statements
A switch statement executes faster than an if/else statement, especially when many nested if/else statements are needed.
With an if/else statement, the code checks to see if a statement is true. If it is true, then it executes a block of code. If it is not true, then it executes a different block of code. On the other hand, a switch statement compares the condition value with many different cases. If there is a match with any of the cases, then the block of code for that specific case is executed. If none of the cases match, then the default block of code is executed.
Overall, the number of comparisons made using a switch/case statement is less than the number of comparisons using an if/else statement.
6. Replace event click with mouseup3
It is best practice to replace the click event listener with the mouseup event listener. The click event does not fire until both the mousedown and mouseup events have fired. So if a user rapidly clicks, the click event can miss some of the interactions. Meanwhile, the mouseup event listener executes before the click event and can catch the rapid clicks from a user. Thus, mouseup performs better than a click event.
7. Event Delegation4
Event listeners, especially mousemove and scroll, are very time expensive. The fewer event listeners you have bound to an element, the faster your JavaScript code. For example, instead of adding an event listener to each item in a list <li>, add the event listener to the overall list <ul>.
Example:
8. Use requestAnimationFrame instead of setTimeout or setInterval for animations4
setTimeout and especially setInterval are time-intensive operations and continue running in inactive tabs. On a mobile device, this leads to poor performance and overuse of the device’s battery. Instead, you should use requestAnimationFrame. requestAnimationFrame is better because when you leave the tab, the animation stops running and it is browser optimized.
To use requestAnimationFrame, you need to have an initial call to requestAnimationFrame that executes some function. Once it executes the code inside this function, it then calls requestAnimationFrame again, which then executes the function again. This keeps looping infinitely.
Example:
If you want the animation to only execute until some condition is met, you can have the requestAnimationFrame call in the exampleFunction inside some conditional.5
9. Throttling4
Event listeners such as scroll, mousemove, and resize can fire hundreds of times in a matter of seconds. As you can imagine, this can greatly slow down your JavaScript performance. Fortunately, there is a JavaScript pattern called throttling that will reduce the rate at which the code inside an event listener is triggered.
Throttling works by using a setTimeout to not allow a function to execute until some minimum wait period is over.
Example:6
In this example, there is a minimum wait period of 300ms before exampleFunction can be called again.
10. Minify7
Minifying your HTML, CSS, and JavaScript code reduces the file sizes by cleaning up unnecessary characters. As a result, the files load faster. Some of the unnecessary characters that are removed are line breaks, comments, and whitespace characters.
There are many different tools, extensions, and plugins you can use to minify your HTML, CSS, and JavaScript code. KeyCDN has a great tutorial that includes a list of some tools you can use to minify code.
These 10 JavaScript tips and tricks are such a simple yet effective way to speed up the execution and enhance the performance of your code. Though there are still many other factors that affect page speed, improving your JavaScript performance will put you one step closer to an optimized website.
Are there any tips you think we missed? Let us know!
And if this is something you need help with for your company’s website, feel free to contact us.
Sources:
- https://www.thinkwithgoogle.com/consumer-insights/consumer-trends/mobile-site-load-time-statistics/
- https://www.w3schools.com/js/js_performance.asp
- https://www.keycdn.com/blog/javascript-performance
- https://ehsangazar.com/optimizing-javascript-event-listeners-for-performance-e28406ad406c
- https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame
- https://programmingwithmosh.com/javascript/javascript-throttle-and-debounce-patterns/
- https://www.keycdn.com/support/how-to-minify-css-js-and-html