How to optimize JavaScript
Nowadays, we use JavaScript in our application or website to create visual effects. Sometimes, it creates these visual effects by manipulating styles or doing calculations such as sorting or searching. However, if we don't use these properly, JavaScript can cause performance issues on our website or application. To minimize these impacts on the website, you should consider the following:
Avoid using
setTimeout
orsetInterval
for visual updates. Instead of these you can userequestAnimationFrame
.Move long-running JavaScript main thread to Web workers.
Use browser development tools to profile JavaScript and assess the impact.
Use micro-tasks to make DOM changes rather than using several frames.
Keep your HTML code clean by removing unwanted
DIV
andSPAN
tags.When updating styles, do them as a batch.
Build DOM separately, before it is added to the page.
Remember to unbind events when they are no longer needed.
Learn about event bubbling. Use
jQuery.bind()
instead ofjQuery...