Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...