Solution 1:

It's not recommended to inline static resources (in your case, the inline javascript) since you can't cache them.

Caching a static resource reduces the size of page loads – thus increasing the page load speed – for returning visitors. However it comes at the cost of an additional HTTP request which should be avoided.

Whenever the static resource is so small that the additional size is negligible in comparison to a HTTP request, then it's actually recommended to keep that resource inline.

It's usually a good idea to keep javascript libraries in external (cacheable) documents, while keeping small amounts of scripts inline.

So, in response to your headline – inline javascript isn't bad per-se. It's a balance whether or not it's worth a HTTP request to cache the resource.

Solution 2:

  • Avoiding inline js is not performance based...but its more about maintainability and separating the presentation layer(html) from the controller layer(js).

  • Having inline js on different pages will make it difficult to maintain for you and others as the project scale increases.

  • Moreover using separate js files you can encourage reusability and modular code design.

  • keeps your html clean and you know where to look when any js error occurs instead of multiple templates.

Solution 3:

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.