【问题标题】:Why insert a static JS dynamically?为什么要动态插入静态 JS?
【发布时间】:2013-08-01 14:26:14
【问题描述】:

在“Google+ Sign-In for server-side apps”帮助页面的“第 3 步:在您的页面中包含 Google+ 脚本”中建议使用以下 sn-p:

    <!-- The top of file index.html -->
    <html itemscope itemtype="http://schema.org/Article">
    <head>
      <!-- BEGIN Pre-requisites -->
      <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js">
      </script>
      <script type="text/javascript">
        (function () {
          var po = document.createElement('script');
          po.type = 'text/javascript';
          po.async = true;
          po.src = 'https://plus.google.com/js/client:plusone.js?onload=start';
          var s = document.getElementsByTagName('script')[0];
          s.parentNode.insertBefore(po, s);
        })();
      </script>
      <!-- END Pre-requisites -->
    </head>
    <!-- ... -->

现在,第二个 SCRIPT 似乎在做什么:

  • 使用静态源创建一个新的 SCRIPT 标记
  • 立即将其插入到文件中第一个 SCRIPT 标记之前。

现在,我的问题是什么? 我的意思是,不会这样做:

<!-- The top of file index.html -->
<html itemscope itemtype="http://schema.org/Article">
<head>
  <!-- BEGIN Pre-requisites -->
  <script async src="https://plus.google.com/js/client:plusone.js?onload=start"></script>
  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
  <!-- END Pre-requisites -->
</head>
<!-- ... -->

实现同样的目标?为什么这个额外的包装函数插入脚本?

【问题讨论】:

  • async 属性存在支持问题。它不适用于 IEstackoverflow.com/questions/1834077/…

标签: javascript


【解决方案1】:

async 属性是一个相当新的开发,大多数版本的 IE 都不支持。 google 的代码本质上是一种模拟异步的跨浏览器方式。

【讨论】:

    猜你喜欢
    • 2021-10-22
    • 2012-09-08
    • 2011-01-14
    • 1970-01-01
    • 1970-01-01
    • 2021-06-07
    • 2014-07-18
    相关资源
    最近更新 更多