Javascript - 内联vs外部脚本 - 有什么区别? [英] Javascript - inline vs external script - what's the difference?

查看:555
本文介绍了Javascript - 内联vs外部脚本 - 有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的网页上散布了一些javascript片段 - 很多都包含在我自己的.js文件中,但是我在网上找到的一些内容直接位于页面上。

I have a few snippets of javascript scattered about my pages - many are contained in my own .js files, however some of the stuff that I've found online sits directly on the page.

我不太熟悉javascript与页面的交互方式 - 添加内联脚本或添加对外部文件的引用有区别吗?

I'm not too familiar with how javascript interacts with a page - is there a difference between adding the script inline or adding a reference to the external file?

推荐答案

使用其中一种方式几乎没有什么区别。真正的区别来自每个人的优势/劣势。

There is little difference in using one or the other way. The real difference comes from the advantages/disadvantages that each one has.

内联脚本


  • 加载在同一页面中,因此无需触发其他请求。

  • 立即执行。

  • async和defer属性无效

  • 使用服务器端动态渲染时可以提供帮助。

  • Are loaded in the same page so is not necessary to trigger another request.
  • Are executed immediately.
  • The async and defer attributes have no effect
  • Can be helpful when you are using a server-side dynamic rendering.

外部脚本


  • 更好地分离顾虑和可维护性。

  • async和defer属性有效,因此如果存在此属性,脚本将更改默认行为。内联脚本无法实现这一点。

  • 下载外部脚本后,浏览器会将其存储在缓存中,因此如果其他页面引用它,则无需额外下载。

  • 可用于按需加载客户端代码并减少整体下载时间和大小。

  • Gives better separation of concerns and maintainability.
  • The async and defer attributes have effect so if this attributes are present the script will change the default behavior. This is not possible with inline scripts.
  • Once a external script is downloaded the browser store it in the cache so if another page reference it no additional download is required.
  • Can be used to load client code on demand and reduce overall download time and size.

这篇关于Javascript - 内联vs外部脚本 - 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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