【问题标题】:Insert into specific place in head tag without using document.write在不使用 document.write 的情况下插入到 head 标签中的特定位置
【发布时间】:2012-11-22 12:36:58
【问题描述】:

这可能是不可能的,但值得一问。我正在将脚本标签动态插入到我页面的head 部分。目前我正在使用document.write,你们中的许多人会皱眉头,但它确实可以很好地完成工作。

但是,出于here 所述的原因,我想找到document.write 的替代方案。

因此,我需要一个可以做到这一点的函数:

<!-- The document.write writes the new script here synchronously so it will block other scripts -->

<script type="text/javascript">
    // Code here that uses the code from the dynamically inserted script
</script>

任何人都可以建议任何使用 jQuery 或纯 javascript 将在页面上插入元素的东西,但也符合这些要求:

  1. 将元素放置在调用函数的位置。例如脚本标签被放置在调用它的脚本标签之后
  2. 脚本会同步加载,因此会阻塞其他脚本,直到它完成

Google 使用他们的Google.load() 方法来做到这一点,他们使用 document.write 吗?肯定不是……

【问题讨论】:

    标签: javascript jquery sinemacula


    【解决方案1】:

    你可以看看这篇文章-http://www.phpied.com/non-onload-blocking-async-js/ facebook 使用类似的脚本来异步加载他们的 SDK。

    它是跨浏览器的,即使页面上的 html 无效(即使缺少 head/body 标签)也可以异步加载脚本。

    这是一个直接来自 facebook 的 SDK 的示例:

      (function(d, debug){
         var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
         if (d.getElementById(id)) {return;}
         js = d.createElement('script'); js.id = id; js.async = true;
         js.src = "//connect.facebook.net/en_US/all" + (debug ? "/debug" : "") + ".js";
         ref.parentNode.insertBefore(js, ref);
       }(document, /*debug*/ false));
    

    您必须进行一些修改,因为它允许您只加载一次脚本(因为if (d.getElementById(id)) {return;})。

    如果我们仔细查看脚本,我们可以看到许多好处:

    • 在您的页面上,您必须有一个 script 标记(因为异步加载的脚本),这就是它获取第一个脚本元素的原因
    • 它会查找已添加的 SDK
    • 它创建具有指定 id 的新脚本元素
    • 设置脚本的src
    • 它将脚本元素插入特定位置
    • 它异步加载脚本以防止页面阻塞
    • 自调用函数为文档对象创建短别名。这使脚本更加紧凑​​。

    【讨论】:

      【解决方案2】:

      你可以用不同的方式来做。正如Link 的各种答案中所述。 但我使用以下

      var load_js = function(data, callback)
                  {
                          var head = document.getElementsByTagName("head")[0];
      
                          var script = document.createElement("script");
                          script.type = "text/javascript";
                          script.src = data;
                          head.appendChild(script);
      
                          if(callback != undefined)
                                  callback();
                  }
      
                  load_js("http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js");
      

      【讨论】:

      • 这是我在使用document.write之前使用的方法,出于某种原因,这不会阻止它之后的脚本运行。无论如何谢谢:-)
      • 我的代码与我最初从您的链接答案中得到的代码完全相同!
      猜你喜欢
      • 2018-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-06
      • 1970-01-01
      • 1970-01-01
      • 2016-04-16
      • 1970-01-01
      相关资源
      最近更新 更多