Make Disqus comment counting work on Infinite Scroll

Without the need of polling, there’s better way to check if there are some changes.

With MutationObserver is what you need.

<!-- Disqus Counts -->
<script id="dsq-count-scr" src="//DISQUSEXAMPLE.disqus.com/count.js" async></script>
<script>
document.getElementById('dsq-count-scr').onload = () => {
	let d = document,
		postFeed = d.querySelector('#site-main .post-feed'),
		postFeedObserver = new MutationObserver(
			mutations =>
				mutations && DISQUSWIDGETS && DISQUSWIDGETS.getCount({ reset: true })
		)

	postFeed && postFeedObserver.observe(postFeed, {
		childList: true
	})
}
</script>
Check: /ghost/#/settings/code-injection
Change DISQUSEXAMPLE to your Disqus name
In this script I attach onload event on the script element then,
assign the parent element I need to Observe,
create an Observer and a function what to do on Mutation and
use Disqus Widget to reset the count,
make sure if parent element exist and attach the Observer with some configurations to observe.

Bonus

Sometimes when I look at the code too long, I feel I want to refactor and make a reusable function.

const attachMutationObserver = (element, callback, options) => {
	const el = typeof element === 'string' ? document.querySelector(element) : element instanceof HTMLElement ? element : undefined
    if (!el) return
    const defaultOptions = { childList: true }
    const elObserver = new MutationObserver(callback)
    elObserver.observe(el, {...defaultOptions, ...options})
    return elObserver
}
Function: attachMutationObserver
const options = {
    attributes: true,
    childList: true,
    characterData: true,
    subtree: true
}
Available attributes in options

Example

const postFeedObserver = attachMutationObserver(
	'#site-main .post-feed',
	mutation => {
		for (let MutationRecord of mutation) {
            // Mutated childList
            if (MutationRecord.type === 'childList') console.log(MutationRecord.addedNodes[0])
        }
	}
)
How to use: attachMutationObserver

Sometime later

postFeedObserver.disconnect()
Disconnect an observer