Wistia On Demand

Used to load wistia resources ONLY when a button is pressed, not on pageload.

by Brian Layman

HTML

<!-- You can dynamically replace "pqsp8lk5qn" in the HTML with any Wistia video ID -->


<div class="wistia_embed wistia_async_pqsp8lk5qn popover=true popoverContent=html silentAutoPlay=allow"><a id="playbutton" href="#" data-wistiaid="pqsp8lk5qn">Play Video</a></div>

JavaScript

function triggerWistia(){ 
  // Dynamically load Wistia JavaScript API
  var ev1 = document.createElement('script');
  ev1.src = '//fast.wistia.com/assets/external/E-v1.js';
  ev1.async = true;
  ev1.charset = 'ISO-8859-1'
  document.head.appendChild(ev1); 
  button = this;
  ev1.onload = function() {
    // the script creates a helper function "_"
    window._wq = window._wq || [];
    // Play video after API has loaded
    data = button.dataset;
    videoId = data.wistiaId;
    _wq.push({ 
    id: videoId, onReady: function(video) {
        video.play();
    }
    });
  };
}

var anchor = document.getElementById('playbutton');
if(anchor.addEventListener) // DOM method
  anchor.addEventListener('click', triggerWistia, false);
else if(anchor.attachEvent) // this is for IE, because it doesn't support addEventListener
   anchor.attachEvent('onclick', function(){ return triggerWistia.apply(anchor, [window.event]); // this strange part for making the keyword 'this' indicate the clicked anchor
});

alert("This function appears to be too complex for jsfiddle, but it works in a live setting. The OnLoad trigger never fires for the added script. So only the second button press works.");