Javascript CreateContexturalFragment在safari中不工作

Javascript CreateContexturalFragment在safari中不工作,javascript,Javascript,safari中的函数(createContextualFragment)有问题 我们需要在正文中添加一些内容,所以我们使用这行代码 代码: document.getElementsByTagName('body')[0].insertBefore(document.createRange().createContextualFragment("<div></div><script src="LINK_SOURCE"></script>"), nul

safari中的函数
(createContextualFragment)
有问题

我们需要在正文中添加一些内容,所以我们使用这行代码

代码:

document.getElementsByTagName('body')[0].insertBefore(document.createRange().createContextualFragment("<div></div><script src="LINK_SOURCE"></script>"), null);
document.getElementsByTagName('body')[0].insertBefore(document.createRange().createContextualFragment(“”),null);
这一行代码在Chrome和Firefox上运行良好,但我们在Safari中的CreateContexturalFragment存在一些问题

Safari中出现错误:

创建上下文片段- asyncronousDocumentWrite2.html:28:115NotSupportedError:DOM异常 9:实现不支持请求的对象类型或 手术


我意识到我的答案来得有点晚,但我最近遇到了类似的情况

我的发现

据 Safari 9.0或9.1不支持Range.CreateContexturalFragment()。不过,它在Safari 10中确实工作得很好

你能做什么?

由于Safari不支持CreateContexturalFragment,我们可以将创建文档片段的责任委托给jQuery。根据您使用的jQuery版本,以下说明了两个执行此操作的选项:

  • jQuery 1.8或更新版本的使用
    document.getElementsByTagName('body')[0].insertBefore($.parseHTML(“”),null)

  • 否则,只需让jQuery知道该做什么
    document.getElementsByTagName('body')[0].insertBefore($(“
    (“”,空)


  • 我发现设置
    range.selectNodeContents(document.createElement('div'))修复了本文中独立指出的问题。
    我的示例用法:

    document.querySelectorAll('.container').forEach((el) => {
      const range = document.createRange();
      range.selectNodeContents(el);
      range.deleteContents();
      range.selectNodeContents(document.createElement('div')); // fix for safari
      el.appendChild(range.createContextualFragment(htmlContent));
    });