为什么内联JavaScript很糟糕? [英] Why inline JavaScript is bad?

查看:134
本文介绍了为什么内联JavaScript很糟糕?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

始终建议通过将所有代码放在 JS 文件中来避免内联Javascript代码,该文件包含在所有页面中。我想知道,如果这不会导致重页中的性能问题。

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
}
}

在每个页面上,我们需要运行这些函数来了解HTML中是否有相应的元素。

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');
};

但是如果将所有函数保存在外部 JS 文件,并通过内联 JavaScript 调用函数,我们只能调用当前页面中所需的函数:

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>

从性能的角度来看,通过内联调用函数是否有益 Javascript (这当然不是最佳做法),以避免调用页面中不需要的大量功能?

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?

当然,这不仅限于函数,因为我们有很多 addEventListener s用于整个网站,在每个页面上触发,不需要它们。

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.

推荐答案

不建议内联静态资源(在你的情况,内联javascript),因为你无法缓存它们

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

缓存静态资源会减少页面的大小负载 - 从而增加页面加载速度 - 用于返回访问者。但是,这需要额外的HTTP请求{href=\"https://developers.google.com/speed/docs/best-practices/request\">应该避免。

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.

每当静态资源如此之小以至于与HTTP请求相比,额外的大小可以忽略不计,那么实际上建议将该资源保持内联。

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.

将javascript库保存在外部(可缓存)文档中通常是一个好主意,同时保持少量内联脚本。

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

所以,回应你的标题 - 内联javascript本身也不错。无论是否值得HTTP请求来缓存资源,这都是一种平衡。

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.

这篇关于为什么内联JavaScript很糟糕?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆