Last active
April 27, 2022 22:20
-
-
Save johndwells/d88e03d01b9adeb79968b5c11e3d94ff to your computer and use it in GitHub Desktop.
Example of Disqus integration with Unpoly & AlpineJS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Alpine from 'alpinejs'; | |
import disqus from './disqus.js'; | |
Alpine.data('disqus', disqus); | |
window.Alpine = Alpine; | |
Alpine.start(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
}); | |
} | |
} | |
}; | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{% 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 %} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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