您的位置:首页 > Web前端 > JavaScript

JS写在.*.js文件中的好处

2009-12-03 11:17 204 查看
JS写在.*.js文件中的好处

先看两个简单的网页文件:
Page1:
<html>
<head>
<title>Title of Page</title>
<script language=”JavaScript”>
function sayHi() {
alert(“Hi”);
}
</script>
</head>
<body>
<!-- body goes here -->
</body>
</html>
Page2:
<html>
<head>
<title>Title of Page</title>
<script language=”JavaScript” src=”external.js”></script>
</head>
<body>
<!-- body goes here -->
</body>
</html>

external.js的文件内容如下:
function sayHi() {
alert(“Hi”);
}
两个网页文件的区别:一个是将JS代码直接内嵌到网页文件,一个是以文件的形式引入js代码。页面代码比较简单,但是这两种不同的方式对系统有比一定的影响,一般是不建议使用内嵌的JS代码具体有如下三个原因:
安全性:Anyone can see exactly what the code is doing just by viewing the source of the page.
If a malicious developer examines the code, he might find security holes that could compromise
the site or application. Additionally, copyright and other intellectual property notices can be
included in external files without interrupting the flow of the page.
代码维护:Maintenance—If JavaScript code is sprinkled throughout various pages, code maintenance
becomes a nightmare. It is much easier to have a directory for all JavaScript files so that when a
JavaScript error occurs, there is no question about where the code is located.
缓存:Browsers cache all externally linked JavaScript files according to specific settings,
meaning that if two pages are using the same file, it is only downloaded once. This ultimately
means faster loading times. Including the same code in multiple pages is not only wasteful, but
also increases the page size and thus increases the download time.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: