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 performance problem in heavy pages.
For example, imagine that we have tens of functions like this
function function1(element){
var el=document.getElementsByClassName(element);
var size=el.length;
if(size==0) return;
for(i=0;i<size;i++){
// the process
}
}
on every page, we need to run the functions to know if there are corresponding elements in the HTML or not.
window.onload = function(){
function1('a');
....
function26('z');
};
but if keeping all functions in an external JS
file, and calling functions through inline JavaScript
, we can call only the functions, which are required in the present page:
<script type="text/javascript">
window.onload = function(){
function6('f');
};
</script>
Doesn't it beneficial from performance point of view to call functions via inline Javascript
(which is of course not best practice) to avoid call of lots of functions, which are not needed in a page?
Of course, this is not limited to functions only, as we have lots of addEventListener
s for the entire website, which are fired on each and every page, where they are not needed.
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.