The inspector panels in most mainstream browsers display the network queries being sent to load that website. This can assist you in determining which JavaScript and CSS resources are loaded on any particular page. Here are links to documentation for each of the following browsers on how to locate and view network activity:
- Chrome
- Microsoft Edge
- Firefox
It is vital to note that unused code cannot be removed from resources that are not hosted by your domain. However, you should be able to optimize the resources that you host.
How to Find Unused Code in Chrome DevTools?
One of Chrome DevTools' best features is the ability to see unused CSS and JavaScript in real-time. This strategy may not be practical at scale, but it can help you rapidly identify resources on a single page that contains useless code.
When you visit a URL, the Coverage tab will tell you how much code was used, versus how much was loaded, from any given resource. To open Chrome DevTools, press Ctrl + Shift + I or click the right mouse button and choose Inspect.
To see it yourself:
- Open Chrome Developers Tools (Ctrl + Shift + I or right-click the mouse button and select Inspect). Then, select the settings icon > More resources > Coverage
- After that, click the Reload (circle arrow) button. Filter the list that appears to only see JavaScript or CSS resources
- Click any resource to see the used and unused code.
Each line of code is color-coded to assist you in distinguishing between useful and unnecessary code:
- Solid green means that a line of code is executed.
- Solid red means it did not execute.
Many CSS resources in the screenshot above are virtually entirely unused styles. A Font Awesome CSS file is one of the items described above. We can go down even further in the DevTools Coverage tab to discover which code/styles are unneeded. The site in question used a total of five icons. However, the CSS file loaded thousands of icon styles on each and every page and post.
We immediately recognise that we could remove the icon styles required by the site and load only those. All of the file paths leading to the current file had to be replaced with a path to the new, much smaller file we created.