在我的 HTML 代码中的何处插入 JavaScript 库和 CSS?
我对 Web 开发并不陌生,当我在互联网上搜索其他主题时,我看到很多人将流行的 JS 库放在他们网站的不同位置.
I am little new to web development and when I was searching internet about other topics, I have seen many people has put popular JS Libraries in Different Places of their websites.
例如:在非常开始或开始 插入JS库</head>
部分.(在加载任何 JS 代码或 CSS 文件之前)
例如:在末尾 插入JS库</head>
部分.(加载所有 JS 代码和 CSS 文件后)
例如:在末尾 插入JS库
部分.(加载所有 JS 代码、文本、图像、视频、CSS 文件等之后...)
所以我的问题是这个.
将以下 JS 库、插件和 CSS 样式表插入(在哪里)到网页以获得更快的加载时间和其他优势的最佳实践是什么?- 请说明原因-
JQuery 及其插件
JQuery and it's Plugins
引导程序 3.js
Modernizr.js
Modernizr.js
Angular.js
还有另一个我不能在这里提到的广泛使用的 JS 库...
And another widely used JS Libraries which I couldn't mention here...
Normalize.css
Normalize.css
reset.css
bootstrap.css + 更多
bootstrap.css + more
谢谢...!
没有所谓的标准"方法.将线条放在哪里的选择归结为一个问题:我什么时候需要图书馆?
There is no so called "standard" method. The choice of where to put the lines boils down to one question: When will I need the library?
你看,网页文件是逐行加载的,让我们以下面的例子来说明我的意思:
You see, web files loads line by line, let's take the following as an example of what I mean:
<script>
document.getElementById("target").innerHTML = "changed"
</script>
<p id="target">unchanged</p>
#target
没有改变,因为脚本在元素之前加载.Web 文件按程序加载.当 JavaScript 行被加载时.它立即执行,但目标元素不是.所以它不能改变元素.
#target
isn't altered because the script was loaded before the element did. Web files loads procedurally. When the line of JavaScript is loaded. It is executed immediately, but the target element isn't. So it couldn't change the element.
即使使用 jQuery,也存在同样的问题:
Even with jQuery, there is the same problem:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$("#target").text("changed");
</script>
<p id="target">unchanged</p>
因此,我们经常使用$(function(){})
.
将 标签或
标签放在正文(前面)或头部的人,希望立即执行脚本,有时他们不会使用
$(function())
或 document.onload
People who put their <script>
tags or <link>
tags in the body (in front) or in the head, wanted to execute the script immediately, sometimes they won't use $(function())
or document.onload
将 标签或
标签放在正文中的人(最终)希望确保所有元素都已加载,然后执行脚本或加载 CSS.
People who put their <script>
tags or <link>
tags in the body (in the end) wanted to ensure all elements are loaded then execute the script or load CSS.
应该先加载jQuery等独立资源,再加载jQuery插件等依赖资源.然后您尝试决定何时开始加载资源,然后将行放置到位.
You should load independent resources such as jQuery first, then load dependent resources such as jQuery plugins. Then you try to decide when you want the resources to start loading, then put the lines in places.
您应该将 CSS 链接放在 标签中,因为您不希望访问者在加载 CSS 文件之前看到无样式的内容.
You should put CSS links in the <head>
tag because you don't want visitors seeing unstyled content before loading the CSS files.
如果你不能决定或者不关心时间,把每个和
标签放在
.
If you can't decide or don't care about the time, put every <script>
and <style>
tags in the <head>
.
这是您可能感兴趣的另一篇文章:加载和执行网页的顺序?
Here is another post you might be interested in: Load and execution sequence of a web page?