How to find out if certain javascript code is actually used?

One of the latest updates from the chrome dev tools now includes a JS and CSS coverage tab that allows you to see your unused code.

https://developers.google.com/web/updates/2017/04/devtools-release-notes

1) Open the Command Menu.
2) Start typing Coverage and select Show Coverage.

I would suggest using spies for this task. They are used in TDD to test if functions are called, so that one could assert if calls are actually happening.

If you are lucky enough those js libraries are initialized in a constructor or in some other way, if so I would suggest you to spy on these init functions.
If not you might want to spy on all functions, but this is painful especially if you have big libraries, in that case I would suggest to go one by one.

In the past I've used Jasmine or Sinon.JS for this task, follows an example:

it('should be able to login', function () {
  spyOn(authobj, 'isEmpty');  
  authobj.login('abc', 'abc');  
  expect(authobj.isEmpty).toHaveBeenCalled();
});

Once you have spies setup on the proper functions then it should be just a matter of checking if they are called or not, you could make a call to mixpanel (first example that comes to mind) with some info about it, so that later on you can see what functions are called and what are not.


I think there's no easy way.

You can remove the script reference, run your site with the browser debugger turned on, and see if there's any "function not found" error.

But you'll have to test every single functionality in your site...


EDIT:

The answer from user li x seems to be the best at this moment.