包含Javascript的最佳方法是什么?

Pau*_*jan 7 html javascript javascript-injection

许多大玩家推荐略有不同的技巧.主要是关于新的安置<script>.

Google Anayltics:

(function() {
  var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
  ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
  var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
Run Code Online (Sandbox Code Playgroud)

Facebook:

(function() {
  var e = document.createElement('script'); e.async = true;
  e.src = document.location.protocol +
    '//connect.facebook.net/en_US/all.js';
  document.getElementById('fb-root').appendChild(e);
}());:
Run Code Online (Sandbox Code Playgroud)

Disqus:

(function() {
    var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
    dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js';
    (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
Run Code Online (Sandbox Code Playgroud)

(发布其他人,我会添加它们)

这些选择是否有任何押韵或理由,或者根本不重要?

Joe*_*ink 3

这些实际上在精神上都是相同的方法。这个想法是推迟脚本,这样它们就不会互相阻塞或文档完整。

在网站内容之后加载额外的外部资源是常见的做法。这样做时,您希望 a) 防止阻塞 onload 事件,以便您的页面更快地“完成”,b) 并行加载资源,正如上面所做的那样。

Steve Souders 声称“渐进增强”是当今网站性能最重要的概念。这个概念建议您尽快交付基本页面,然后根据需要交付额外的内容/服务,无论是在加载事件上还是在用户请求时。

现在有一些框架可以提供帮助。参见http://headjs.com/