I’ve using something like this:
var loadDisqus = function() {
var disqus_shortname = 'disqus-forum-identifier';
var config = document.getElementById('load-comments').dataset;
if(typeof DISQUS == 'undefined') {
var e = document.createElement("script");
e.type = "text/javascript";
e.async = true;
e.src = "//" + disqus_shortname + ".disqus.com/embed.js";
(document.getElementsByTagName("head")[0] ||
document.getElementsByTagName("body")[0])
.appendChild(e);
e.onload = function() {
resetDisqus(DISQUS,config);
};
} else {
resetDisqus(DISQUS,config);
}
};
var resetDisqus = function(DISQUS,config) {
return DISQUS.reset({
reload: true,
config: function() {
this.page.identifier = config.identifier;
this.page.url = config.url;
this.page.title = config.title;
}
});
};
window.addEventListener('load',function(){
var hash = window.location.hash;
if((hash.startsWith('#disqus') || hash.startsWith('#comment'))) {
loadDisqus();
}
});
Note this line:
var config = document.getElementById('load-comments').dataset;
I’ve added the disqus config data to the dataset of a element loaded within the ajax content; it could be any element, for example a button:
<?php
$dsq_config = [
'identifier' => get_the_ID() . ' ' . wp_get_shortlink(),
'url' => get_the_permalink(),
'title' => get_the_title()
];
?>
<button id="load-comments" data-identifier="<?php echo esc_attr($dsq_config['identifier']); ?>" data-url="<?php echo esc_attr($dsq_config['url']); ?>" data-title="<?php echo esc_attr($dsq_config['title']); ?>">Load comments</button>
<div id="disqus_thread"></div>
Then, loadDisqus()
can be executed after the ajax content has been injected into the document; for example, attaching that function to the button’s click event.
document.getElementById('load-comments').addEventListener('click', loadDisqus);
It seems to work, but it has been tested only by me, it is possible I’ve missed something.