Search code examples
jqueryajaxjquery-ui-dialoggetscript

getScript - execute on dialog confirmation


I have script that when loaded using the traditional standalone method

<Script src="wthvideo/wthvideo.js"></script>

works without a problem. But when I attempt to load it using Ajax/getScript() method after click confirmation on a JqueryUi.Dialog box - the script will not run/load and developer tools doesn't show the script getting called.

Other components such as the fadeIn() effects trigger just fine - only the getScript() fails. Looking at the JqueryUi API i dont see where im implimenting it wrongly, can someone shed some light on why the script won't load/fire?

$( "#fsr" ).dialog({
      resizable: false,
      height: 350,
      width: 550,
      modal: true,
      buttons: {
        "Allow Fullscreen": function() {
          launchFullscreen(document.documentElement);
          $( this ).dialog( "close" );
            $('#title span').fadeIn(2000);
            $('#titlesub span').fadeIn(2800);
            setTimeout(function(){$('#globe').addClass("globefc");}, 1500);
            /*$.ajax({
            url: "wthvideo/wthvideo.js",
            async: false,
            dataType: "script",
            success: success
            });*/
            $.getScript("wthvideo/wthvideo.js");
            setTimeout(function(){  $('#wthvideo').remove();}, 39500);

        },
        Cancel: function() {
          $( this ).dialog( "close" );
        }
      }
    });

Solution

  • Your script (wthvideo.js) takes on the form:

    function wthplayer() {
      ...
    }
    
    if (window.addEventListener) {
        window.addEventListener("load", wthplayer, false);
    } else if (window.attachEvent) {
        window.attachEvent("onload", wthplayer);
    } else {
        window.onload = wthplayer;
    }
    

    So, you are only doing 2 things:

    1. Defining a function
    2. Telling the browser to execute the function when the "onload" event fires.

    Your problem is that you are dynamically loading the wthvideo.js script long after the browsers onLoad event has fired. This works fine if you are loading the script prior to the onLoad event, which is why you have no problem when using a <script> tag.

    There are many ways to fix this. One quick way is to check if the onLoad event has already executed and execute your function immediately like so:

    function wthplayer() {
      ...
    }
    
    if (document.readyState === 'complete') {
      wthplayer();
    }
    else {
      if (window.addEventListener) {
        window.addEventListener("load", wthplayer, false);
      } else if (window.attachEvent) {
        window.attachEvent("onload", wthplayer);
      } else {
        window.onload = wthplayer;
      }
    }