【问题标题】:Why 'inject with insertBefore avoid appendChild errors'?为什么'用 insertBefore 注入避免 appendChild 错误'?
【发布时间】:2020-06-24 23:13:12
【问题描述】:

How, When, And Why Script Loaders Are Appropriate的文章上,我发现以下评论没有明确解释:

// Very simple asynchronous script-loader

// Create a new script element
var script      = document.createElement('script');

// Find an existing script element on the page (usually the one this code is in)
var firstScript = document.getElementsByTagName('script')[0];

// Set the location of the script
script.src      = "http://example.com/myscript.min.js";

// Inject with insertBefore to avoid appendChild errors
firstScript.parentNode.insertBefore( script, firstScript );

他们通过使用insertBefore 而不是appendChild 避免了哪些错误?

为什么appendChild 会导致任何错误?

【问题讨论】:

    标签: javascript appendchild


    【解决方案1】:

    看起来这是针对 IE6 中的一个错误,并且是为了避免缺少 head 标签的问题。

    对脚本注入技术的良好描述以及一点历史和背景:http://www.stevesouders.com/blog/2010/05/11/appendchild-vs-insertbefore/

    具体本期:https://bugs.jquery.com/ticket/2709

    head = document.getElementsByTagName ("head")[0] || 
        document.documentElement;
    // Use insertBefore instead of appendChild to circumvent an IE6 bug.
    // This arises when a base node is used (#2709 and #4378).
    head.insertBefore(script, head.firstChild);
    

    顺便说一句,我在 IE6 支持方面做了很多工作,但我从来没有遇到过这个问题。由于其他原因,我避免使用 head 标签,并使用了 insertBefore,以便在需要时更容易清理注入的脚本,所以我想我很幸运。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-15
      • 1970-01-01
      • 1970-01-01
      • 2017-11-10
      相关资源
      最近更新 更多