【问题标题】:Broken script when added to headers in WordPress在 WordPress 中添加到标题时脚本损坏
【发布时间】:2019-06-11 02:32:39
【问题描述】:

我编写了一个 WordPress 插件,它提供向标题添加脚本。当我尝试添加我们服务的代码 sn-ps 时

<script src="url/index.js"></script>
<script>
  var foo = new window.Name("token");
  foo.init();
</script>

首先,我遇到了一些错误。

Uncaught (in promise) TypeError: Cannot read property 'appendChild' of null
at r.<anonymous> (index.js:176)
at L (index.js:47)
at Generator._invoke (index.js:47)
at Generator.t.(:8000/anonymous function) [as next] (url/index.js:47:4580)
at r (index.js:174)
at c (index.js:174)
at index.js:174
at new Promise (<anonymous>)
at new r (index.js:36)
at r.<anonymous> (index.js:174)

Uncaught TypeError: Cannot read property 'appendChild' of null
at i.value (index.js:178)
at r.value (index.js:180)
at (index):41

.

url 返回我们由 Babel 渲染的脚本代码。

当我在脚本前添加任何标准 html 代码,如 &lt;html&gt;&lt;/html&gt;&lt;p&gt;&lt;/p&gt;

<p></p>
<script src="url/index.js"></script>
<script>
  var foo = new window.Name("token");
  foo.init();
</script>

效果很明显。任何html代码呢?我无法理解。我通过添加&lt;html&gt;&lt;/html&gt; 来解决它,而不会损坏网站。我尝试学习问题。

【问题讨论】:

    标签: javascript html wordpress plugins header


    【解决方案1】:

    如果不查看url/index.js 文件中的内容,很难判断,但它可能会尝试将节点附加到&lt;body&gt; 元素,或者它存在之前的子元素。如果您在 &lt;head&gt; 部分中调用此脚本,它还不存在。

    &lt;p&gt;&lt;/p&gt; 修复它的原因是如果浏览器收到以下内容:

    <head>
      <script>
        console.log(document.body);
      </script>
    </head>
    

    它认为它是无效的 HTML,因此它重新解释为:

    <html>
      <head>
        <script>
        console.log(document.body);
        </script>
      </head>
      <body></body>
    </html>
    

    - 脚本运行时正文不存在,因此控制台记录null

    如果浏览器收到:

    <p>Paragraph</p>
    <head>
      <script>
        console.log(document.body);
      </script>
    </head>
    

    ...又是无效的 HTML,并被重新解释为

    <html>
      <head></head>
      <body>
        <p>Paragraph</p>
        <script>
          console.log(document.body);
        </script>
      </body>
    </html>
    

    ...并且body元素在脚本运行时存在,所以它会将body元素记录到控制台。

    总而言之:您需要确保所有 HTML 都是有效的,并且您的脚本只会尝试将某些内容附加到已经存在的元素。

    【讨论】:

    • 您如何看待添加&lt;p&gt;&lt;/p&gt; 的解决方案?什么关系?
    • 我已经更新了我的答案,全面解释了为什么会“修复”它。但是,请不要只添加段落标签,您会创建更多无效的 HTML。通过验证您的所有 HTML 并修复您的 javascript 来正确解决问题。如果您由于某种原因无法更改您的 javascript,请将其放在网站的页脚,而不是 head 部分。这将确保页面上的所有元素在脚本运行之前都存在。
    • 感谢您的关注。这是有道理的。我在页脚部分添加了它。有用。我明白了,谢谢。
    猜你喜欢
    • 2015-10-15
    • 2016-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-12
    • 1970-01-01
    • 2019-11-07
    • 1970-01-01
    相关资源
    最近更新 更多