Javascript document.createElement('script') 与 <script src="">
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14666658/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
document.createElement('script') vs <script src="">
提问by webjay
Why is it that services like Google and Facebook use document.createElement('script')instead of just <script>?
为什么像 Google 和 Facebook 这样的服务使用document.createElement('script')而不是仅仅使用<script>?
The Google Analytics snippet:
谷歌分析代码段:
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
could be written as just:
可以写成:
<script src="//www.google-analytics.com/ga.js" type="text/javascript"></script>
and Facebook's like button:
和 Facebook 的点赞按钮:
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_GB/all.js#xfbml=1&appId=xxx";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
could be simplified as just:
可以简化为:
<script src="//connect.facebook.net/en_GB/all.js#xfbml=1&appId=xxx"></script>
I know there's some playing safe in them, but other than that I don't see why we shouldn't use the HTML5 ones?
我知道其中有一些是安全的,但除此之外,我不明白为什么我们不应该使用 HTML5 的?
回答by Salman A
The <script src=...>blocks the browser while document.createElement('script')loads the JavaScript asynchronously; this is the primary reason.
在异步加载 JavaScript 的<script src=...>同时阻塞浏览器document.createElement('script');这是首要原因。
The <script src=...>tag blocks browser from displaying rest of the page until the script is loaded and executed. This ensures that scripts are executed in correct order and any document.write()in that script work as expected. However this creates a laggy browsing experience for the user.
该<script src=...>标签阻止浏览器显示页面的其余部分,直到加载并执行脚本。这确保脚本以正确的顺序执行,并且document.write()该脚本中的任何脚本都按预期工作。但是,这会为用户带来滞后的浏览体验。
When the script is loaded asynchronously, the browser can download the script without blocking the page display. This improves the browsing experience dramatically.
当脚本异步加载时,浏览器可以在不阻塞页面显示的情况下下载脚本。这极大地改善了浏览体验。
To load the scripts asynchronously one can use HTML markup:
要异步加载脚本,可以使用 HTML 标记:
<script src="..." async defer></script>
The asyncattribute was introduced in HTML5 while the deferattribute can be added as a fallback for older versions of IE. This document describes how async and defer attribute work.
该async属性是在 HTML5 中引入的,而该defer属性可以作为旧版本 IE 的后备添加。本文档描述了 async 和 defer 属性的工作原理。
Alternately, one can use JavaScript to build a script tag:
或者,可以使用 JavaScript 构建脚本标记:
var s = document.createElement('script');
s.src = "...";
document.getElementsByTagName("head")[0].appendChild(s);
JavaScript generated script tags work in most browsers even if they do not understand the asyncattribute or .async = trueproperty.
JavaScript 生成的脚本标签可以在大多数浏览器中工作,即使它们不理解async属性或.async = true属性。
About schemeless URIs (//example.com/script.js): schemeless URIs seem to work almost everywhere (see this question).
关于无方案 URI ( //example.com/script.js):无方案 URI 似乎几乎适用于所有地方(请参阅此问题)。
About the Google Analytics example: both old and new code use JavaScript to detect the protocol then load http://www.or https://ssl.which is not possible via HTML markup.
关于 Google Analytics 示例:旧代码和新代码都使用 JavaScript 来检测协议然后加载,http://www.或者https://ssl.这是不可能通过 HTML 标记实现的。
回答by Hogan
In addition to Salman A's excellent point about deferred loading this technique is used when the static solution won't work.
除了 Salman A 关于延迟加载的出色观点之外,当静态解决方案不起作用时,还会使用此技术。
- I've seen it used when caching is an issue (a unique time based hash is added to the URL)
- In the case of the google link shown above SSL can be dynamically turned on.
- In the facebook code it checks if the script already exists (this can avoid bugs where the same script is loaded twice).
- 我已经看到它在缓存出现问题时使用(在 URL 中添加了一个基于时间的唯一哈希)
- 在上面显示的 google 链接的情况下,可以动态打开 SSL。
- 在 facebook 代码中,它检查脚本是否已经存在(这可以避免相同脚本加载两次的错误)。
There can be other reasons too. All of them have to do with needing a dynamic solution.
也可能有其他原因。所有这些都与需要动态解决方案有关。
回答by Parv Sharma
yes that can be written in a script tag but the examples you have quoted are the ones where the website is providing user with some code block which they are required to copy paste in their websites
so injecting is better because this way the website like google and facebook
1.as you can see in the googles example you have provided it dynamically detectes http OR https
2. this way websites can check wethther the same script is present and then choose not to download it again as being done in facebooks example
3. have more control over what is being injected. as the script that is being injected can be changed dynamically without users being required to change the url of the script being injected and this is necessary as many browsers just keep the scripts in cache
4.this way these websites keep their codes sort and less prone to user interference
是的,可以写在脚本标签中,但您引用的示例是网站向用户提供一些代码块的示例,他们需要将这些代码块复制粘贴到他们的网站中,
因此注入更好,因为这样的网站像 google 和facebook 1.
正如您在 googles 示例中所看到的,您提供它动态检测 http 或 https
2。这样网站可以检查是否存在相同的脚本,然后选择不再次下载它,就像在 facebook 示例
3 中所做的那样。更好地控制注入的内容。因为可以动态更改正在注入的脚本,而无需用户更改正在注入的脚本的 url,这是必要的,因为许多浏览器只是将脚本保存在缓存中
4.这样这些网站保持他们的代码排序并且不太容易受到用户干扰

