JS Performance Tips
26 October, 2020
- getElementsByClassName & getElementsByTagName are faster than querySelecterAll
- Do not attach event handlers to window scroll events, as this event may fire a lot and it may slow down performance for the entire page.
[Solution:] Use a timer-based logic or use throttle.
- Accessing DOM is SLOW, so cache the dom element after a query.
- To run long computation from JS on the main thread we need to break the task into timers.
OR use a web worker. Do not overuse web workers as to and fro passing messages to web workers can be a bottleneck again.
- Split code into modules which are critical for the page load and modules which can be lazy loaded.
Lazy loading modules in JS
- Load a module on use click, works better for performance.
- We can also prefetch the JS files and keep them in memory and if use clicks, we can parse the JS code, this will be faster.
- To increase speed we may load the entire JS file (unsplitted into modules) and have parts of the file commented out so that the parser ignores it. The parser is also responsible for the load time of the JS resource. As and when needed uncomment the JS code and parse it.