【问题标题】:"Cannot read property 'appendChild' of null" with Disqus on Backbone website“无法读取 null 的属性‘appendChild’”,Disqus 在 Backbone 网站上
【发布时间】:2017-04-07 03:23:47
【问题描述】:

我在 Backbone 上有一个网站。 当我尝试执行 Disqus 代码时,我得到了

未捕获的类型错误:无法读取 null 的属性“appendChild”

我该如何解决?为什么会这样?

var disqus_shortname = 'mysite';

/* * * DON'T EDIT BELOW THIS LINE * * */
(function() {
  var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
  dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
            (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();

控制台:

undefined
embed.js:1 Unsafe attempt to redefine existing module: BASE
embed.js:1 Unsafe attempt to redefine existing module: apps
embed.js:1 Unsafe attempt to redefine existing module: get
...

embed.js:1 Unsafe attempt to redefine existing module: configAdapter
embed.js:1 Unsafe attempt to redefine existing module: removeDisqusLink
embed.js:1 Unsafe attempt to redefine existing module: loadEmbed
embed.js:1 Unsafe attempt to redefine existing module: reset
embed.js:1 Uncaught TypeError: Cannot read property 'appendChild' of null

【问题讨论】:

  • 似乎您没有在 HTML 中定义 headbody 标记。

标签: javascript backbone.js disqus


【解决方案1】:

对于那些在 2015 年才发现的,除了在缺少“head”或“body”时发生,当您的页面某处没有以下 div 时,也会发生此错误:

<div id="disqus_thread"></div>

将该 div 放在您希望 disqus 线程实际出现的位置。

【讨论】:

  • 这为我解决了一个类似的问题。我遇到了“appendChild of null”错误,我刚刚意识到我到处都包含了 disqus 脚本,但每个页面上都没有 cmets。现在我只是将代码包装在if($("#disqus_thread").length){ ... } 中,我很好。
【解决方案2】:

由于某种原因,您的文档似乎同时缺少 headbody

试试这个:

(function() {
    var dsq = document.createElement('script');
    var head = document.getElementsByTagName('head')[0];
    var body = document.getElementsByTagName('body')[0];

    dsq.type = 'text/javascript';
    dsq.async = true;
    dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';

    console.log('head', head);
    console.log('body', body);

    (head || body).appendChild(dsq);
}());

然后查看控制台。

【讨论】:

  • 但仍然记录“未捕获的类型错误:无法读取 null 的属性 'appendChild'”
  • 这个错误来自 embed.js 截图 - cloud.mail.ru/public/9iFg/8t8pomZXd
  • 是的,我们需要更多信息来解决您的问题,此答案旨在帮助您诊断问题所在。在错误上方,您是否看到“头部”或“身体”旁边的任何内容?如果你直接在控制台那里写document.getElementsByTagName('head')[0],你会看到什么?
  • 头部和身体存在。
  • 好的,但是从该函数中登录时是否存在headbody
【解决方案3】:

我是这样解决的:

// Only if disqus_thread id is defined load the embed script
if (document.getElementById('disqus_thread')) {
    var your_sub_domain = ''; // Here goes your subdomain
    var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
    dsq.src = '//' + your_sub_domain + '.disqus.com/embed.js';
    (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
}

感谢@boutell 和@June 提供线索。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-12
    • 2023-03-14
    相关资源
    最近更新 更多