"Cannot read property 'appendChild' of null" 在 Backbone 网站上使用 Disqus

"Cannot read property 'appendChild' of null" with Disqus on Backbone website

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

Uncaught TypeError: Cannot read property 'appendChild' of null

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

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

由于某种原因,您的文档似乎缺少 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);
}());

然后查看控制台。

对于那些在 2015 年才发现这个问题的人来说,除了缺少 "head" 或 "body" 时会发生此错误之外,当您在某处没有以下 div 时也会发生此错误你的页面:

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

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

我是这样解决的:

// 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 提供线索。