An Interest In:
Web News this Week
- March 20, 2024
- March 19, 2024
- March 18, 2024
- March 17, 2024
- March 16, 2024
- March 15, 2024
- March 14, 2024
Speed Up Your Javascript With These Simple Methods
If your Javascript code is running slower than you'd like, or if you just want to know how to make your code faster regardless, stick around for some easy to implement ways of making your Javascript run faster
Bottom of Webpage
To make your webpage's loading faster, make sure your Javascript code is at the bottom of your HTML webpage's body
tag.
Web Workers
If your webpage uses time-intensive Javascript operations, web workers can save you a lot of time. Using web workers can mean the difference between an unresponsive and slow webpage, and a smooth running and fast webpage.
Web workers are separate threads created by your main Javascript code to work in parallel with the main process.
You can read about web workers and their JS implementation here
Saving DOM Elements
When manipulating the same DOM element multiple times, to speed up your code, you should define it once and then keep referencing it.
No
const el1 = document.getElementById("demo");el1.style.color = "green";const el1 = document.getElementById("demo");el1.style.color = "blue";const el1 = document.getElementById("demo");el1.style.color = "pink";
Yes
const el1 = document.getElementById("demo");el1.style.color = "green";el1.style.color = "blue";el1.style.color = "pink";
Reduce Library Dependancies
Loading libraries in JS can take up a lot of time, make sure to remove any unneeded library dependancies in your Javascript code.
Reduce Loop Activity
In Javascript, loops can take quite a lot of time to finish running. A simple way to make your JS loops run faster is by defining the loop parameters before the loop itself.
No
for (let g = 0; g < arr.length; g++) {
Yes
let arrlen = arr.length;for (let g = 0; g < arrlen; g++) {
This will speed up your for loop because now, instead of getting the length of the "arr" array every single iteration, it will get that value once and reuse it throughout every iteration.
Avoid Global Variables
Global variables can slow down your JS code. When defining a variable for the first time, make sure to add the var
prefix to make it a local variable instead of a global one.
No
v1 = 9
Yes
var v1 = 9
Conclusion
I hope that these were helpful.
Original Link: https://dev.to/code_jedi/speed-up-your-javascript-with-these-simple-methods-1509
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To