I have been trying to save resources on the page by not loading the Zendesk Widget unless required.
If i manually add to a page the following tag everything works just fine:
<script id="ze-snippet" src="https://static.zdassets.com/ekr/snippet.js?key=[MyKey]> </script>
As part of my page i have somewhere a div tag always present:
<div id="ze-snippet"> </div>
What i would like to have is, to do a "dynamic script load" of that <script>
tag when a user clicks a button.
My current attempt looks like this:
window.onload = function () {
var zendeskWidgetOn = false;
document.getElementById('enable-zendesk-widget').addEventListener('click', function( event ) {
if (!zendeskWidgetOn) {
zendeskWidgetOn=true;
(function(d, script) {
script = d.createElement('script');
script.type = 'text/javascript';
script.async = true;
script.onload = function(){
console.log('script finished loading ...');
};
script.src = 'https://static.zdassets.com/ekr/snippet.js?key=[my key]';
d.getElementsByTagName('head')[0].appendChild(script);
}(document));
}
}, false);
};
The error i keep getting and i can't for the life of me figure out how to work around it is:
To have the widget script load only upon clicking the button, you just have to insert this to your html:
<script>
function loadZendeskWidget() {
var script = document.createElement('script');
script.type = 'text/javascript';
script.id = 'ze-snippet';
script.async = true;
script.src = 'https://static.zdassets.com/ekr/snippet.js?key=<key>';
document.getElementsByTagName('head')[0].appendChild(script);
};
</script>
Just replace "key" with your own widget key.
Hope this helps.