Javascript Provides interaction to our websites, but it also blocking assets, which means if it is not loaded completely if a JS is loading it will block any other processes like rendering, etc. Hence it is very important to how efficiently we use JS in our Frontend Code below are some ideas that can be used to improve Frontend Performance by optimizing Javascript.
1. Break JS into Small Chunks – Modern Build Tools like Webpack, and Parcel allows us to bundle our Code but also allow us to create Smaller Bundle Chunks we need to break our Javascript and decide which parts are critical and which ones are less critical based on that we need to only load the critical parts in the beginning and later parts as and when they are required.
2. Optimize Chunks size – These JS Code chunks can be minified, uglified, etc to further reduce the size of the JS Delivery over the network. Also, the Network delivery can be optimized through GZIP or Brotli (Separate Article for this)
3. Remove Unused Code – Many times in our JS code we add libraries that are not fully required but we include the entire library to use the functionality. Removing unused Code is also called Dead Code Elimination or Tree Shaking. (Some Articles take these two as separate things) But the idea is to eliminate the code which is not required here again Build Tools like Webpack, Rollup, etc can do the magic and likewise, some minifiers like terser can help eliminate the dead code. But while developing we should also be diligent in only using libraries and external code efficiently.
4. Use PRPL Pattern – There is something called a Critical Path when it comes to Web Applications. Which means what are the most essential resources required to quickly render the view in front of the user? Optimizing for Critical Path should be the main focus of any Frontend Developer. PRPL is one such pattern that allows us to write code for Critical Path. It is defined below as.
PreLoad Critical Resources.
Render the initial Route as soon as possible.
Pre-Cache often visited assets and routes.
Lazy Load – Remaining assets and routes.
One thought on “Frontend Performance Optimization – Part 2 (Javascript)”