javascript

Javascript to run a function after script file is loaded

The below javascript code can be used to run a callback function only after the script file is fully loaded.

function load_script_file( file_url, callback ) {
  var script = document.createElement( "script" )
  script.type = "text/javascript";
  if(script.readyState) { // If browser(IE) is < 9
    script.onreadystatechange = function() {
      if ( script.readyState === "loaded" || script.readyState === "complete" ) {
        script.onreadystatechange = null;
        callback();
      }
    };
  } else {
    script.onload = function() {
      callback();
    };
  }

  script.src = file_url;
  document.getElementsByTagName( "head" )[0].appendChild( script );
}


// load script file and run the callback function 
load_script_file('script_file_path', function() {
    console.log("Script file is loaded");
});
Was this helpful?