Why inline JavaScript is bad?

2020-01-27 05:15发布

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.

7条回答
地球回转人心会变
2楼-- · 2020-01-27 06:12

Inline styles/script gets muddled with html content and can get hard to differentiate. One of the the keys to having maintainable code in web development is writing code that is easily readable by someone who didn't write it. Mixing script tags into your html can make it very hard to find a function that is affecting the rest of you code. Putting Javascript in .js files and Styles in CSS files makes code cleaner more readable.

查看更多
登录 后发表回答