Skip to content

Instantly share code, notes, and snippets.

@johndwells
Last active April 27, 2022 22:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johndwells/d88e03d01b9adeb79968b5c11e3d94ff to your computer and use it in GitHub Desktop.
Save johndwells/d88e03d01b9adeb79968b5c11e3d94ff to your computer and use it in GitHub Desktop.
Example of Disqus integration with Unpoly & AlpineJS
import Alpine from 'alpinejs';
import disqus from './disqus.js';
Alpine.data('disqus', disqus);
window.Alpine = Alpine;
Alpine.start();
import loadjs from 'loadjs';
export default (script = '', config = {}) {
const c = {
url : '',
identifier : '',
title : '',
...config
};
const disqus_config = function () {
this.page.url = c.url;
this.page.identifier = c.identifier;
this.page.title = c.title;
};
return {
init() {
if(window.DISQUS === undefined) {
window.disqus_config = disqus_config;
loadjs([script], {
before: function(path, scriptEl) {
scriptEl.setAttribute('data-timestamp', new Date());
}
});
} else {
window.DISQUS.reset({
reload: true,
config: disqus_config
});
}
}
};
};
{% set url = url|default(craft.app.request.getAbsoluteUrl()) %}
{% set identifier = identifier|default(craft.app.request.getPathInfo()|kebab) %}
{% set title = title|default(siteName) %}
{% set handle = getenv('DISQUS_SITE_HANDLE')|default('') %}
{% if handle %}
{% set disqusConfig = {
url : url,
identifier : identifier,
title : title,
} %}
<div x-data="disqus('https://{{ handle }}.disqus.com/embed.js', {{ disqusConfig|json_encode }})"
id="disqus_thread">
</div>
{% endif %}
@johndwells
Copy link
Author

The trick I found with getting Disqus to work well within an "SPA" environment is to check to see if it's already been loaded on the page, and if it has to use window.DISQUS.reset() as mentioned here:

https://help.disqus.com/en/articles/1717163-using-disqus-on-ajax-sites

I also used loadJS to load Disqus on demand, which also allowed me to inject it's script tag with the necessary data-timestamp attribute, as mentioned here:

https://help.disqus.com/en/articles/1717084-javascript-configuration-variables

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment