Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why inline JavaScript is bad?

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 addEventListeners for the entire website, which are fired on each and every page, where they are not needed.

like image 905
Googlebot Avatar asked Sep 05 '25 11:09

Googlebot


2 Answers

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.

like image 128
Nils Kaspersson Avatar answered Sep 08 '25 14:09

Nils Kaspersson


  • 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.

like image 36
Abhidev Avatar answered Sep 08 '25 13:09

Abhidev