It is always recommended to avoid inline Javascript codes by putting all codes in a JS
file, which is included in all pages. I wonder, if this does not cause pe
You should read about unobtrusive javascript, http://en.wikipedia.org/wiki/Unobtrusive_JavaScript.
There are other solutions for not loading all the javascript files in your assets directory for each webpage, one called requirejs that should check out, http://requirejs.org/ .
Moreover as a general rule of thumb you should not be adding all your event listeners when page loads, what about dom objects that don't exist? It will throw up javascript errors and will break your code more than usual.
IMO it depends on the page. Sometimes for a specific page and script is small, it does not make sense to put in an external file.
According to Addy Osmani
's "The cost of JavaScript
" presentation at #PerfMatters Conference 2019
one of the recommendation was to Avoid large inline scripts.
Avoid large inline scripts (as they’re still parsed and compiled on the main thread). A good rule of thumb is: if the script is over 1 kB, avoid inlining it (also because 1 kB is when code caching kicks in for external scripts).
So if you inline script is less then 1 KB - it's fine, otherwise - avoid it.
Here is the source: The cost of JavaScript in 2019