Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically Script Loading Zendesk Widget

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: enter image description here

like image 730
Victor Albu Avatar asked Oct 23 '25 06:10

Victor Albu


1 Answers

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.

like image 112
abahet Avatar answered Oct 24 '25 20:10

abahet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!