You need to enable JavaScript to run this app. 使用appendChild插入OtAutoBlock.js能否保证其优先于其他脚本加载
优惠活动
大模型
产品
解决方案
定价
更多

使用appendChild插入OtAutoBlock.js能否保证其优先于其他脚本加载

问题结论

你当前的appendChild实现无法保证OtAutoBlock脚本优先于其他脚本加载,核心问题不是插入位置,而是动态创建脚本的默认加载特性。

原代码的问题说明
  • appendChild的行为是将节点追加到父元素(此处为head)的子节点末尾:你当前的插入逻辑是在head内的第一个内联脚本中执行的,此时浏览器还未解析到后面的其他<script>标签,所以插入的OtAutoBlock脚本会排在当前内联脚本之后、其他静态声明的脚本之前,位置上确实在其他脚本前面,但依旧不满足优先执行的要求
  • 动态创建的带src的<script>标签默认开启async属性,加载过程不阻塞后续HTML解析/脚本执行,后续的脚本会在OtAutoBlock加载完成前就运行,完全达不到规避未同意前追踪的要求
修复方案

要保证OtAutoBlock优先按顺序加载、且阻塞后续脚本执行,修改两处逻辑即可:

  1. 给动态创建的脚本显式关闭async特性
  2. 如果需要保证OtAutoBlock是整个head的第一个脚本,可替换appendChild为insertBefore插入到head最开头

修正后的代码如下:

<!DOCTYPE html>
<html lang="en">
  <head>
    <!-- OneTrust Cookies Consent Notice -->
    <script type="text/javascript">
      if ("%REACT_APP_COOKIE_BAR%" === "true") {
        var otAutoBlock = document.createElement("script");
        otAutoBlock.setAttribute("type", "text/javascript");
        otAutoBlock.setAttribute("src", "https://cdn.cookielaw.org/consent/c4337328/OtAutoBlock.js");
        // 关闭异步加载,按插入顺序执行且阻塞后续内容
        otAutoBlock.async = false;
        
        var otSDKStub = document.createElement("script");
        otSDKStub.setAttribute("type", "text/javascript");
        otSDKStub.setAttribute("src", "https://cdn.cookielaw.org/scripttemplates/otSDKStub.js");
        otSDKStub.setAttribute("charset", "UTF-8");
        otSDKStub.setAttribute("data-domain-script", "c4337328");
        otSDKStub.async = false;

        // 插入到head最开头,保证是第一个加载的脚本
        document.head.insertBefore(otSDKStub, document.head.firstChild);
        document.head.insertBefore(otAutoBlock, document.head.firstChild);

        function OptanonWrapper() { }
      }
    </script>

    <script type="text/javascript">
      /* [现在会在OtAutoBlock加载完成后才执行] */
    </script>

  </head>

  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
  </body>
</html>
验证方式

打开浏览器控制台的网络面板,筛选「JS」资源,即可看到OtAutoBlock是第一个发起请求、第一个加载完成的JS脚本,后续脚本的请求/执行都在它之后。

内容的提问来源于stack exchange,提问作者Joey Coder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.16 20:45:00