"无法在Backbone网站上使用Disqus查看属性'appendChild'of null"

der*_*nov 5 javascript disqus backbone.js

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

未捕获的TypeError:无法读取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);
})();
Run Code Online (Sandbox Code Playgroud)

安慰:

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
Run Code Online (Sandbox Code Playgroud)

Tom*_*ell 19

对于那些刚刚在2015年发现这一点的人,除了缺少"head"或"body"之外,当您在页面中的某个地方没有以下div时,会发生此错误:

<div id="disqus_thread"></div>
Run Code Online (Sandbox Code Playgroud)

把div放在你想要实际出现的disqus线程的地方.

  • 这为我解决了类似的问题.我有"appendChild of null"错误,我刚刚意识到我在所有地方都包含了disqus脚本,但没有在每个页面上发表评论.现在我把代码包装在`if($("#disqus_thread").length){...}`中,我很好. (5认同)

Ale*_*lan 3

由于某种原因,您的文档似乎同时缺少 ahead和 a body

尝试这个:

(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);
}());
Run Code Online (Sandbox Code Playgroud)

然后查看控制台。