Call javascript function after script is loaded

you can achieve this without using head.js javascript.

function loadScript( url, callback ) {
  var script = document.createElement( "script" )
  script.type = "text/javascript";
  if(script.readyState) {  // only required for IE <9
    script.onreadystatechange = function() {
      if ( script.readyState === "loaded" || script.readyState === "complete" ) {
        script.onreadystatechange = null;
        callback();
      }
    };
  } else {  //Others
    script.onload = function() {
      callback();
    };
  }

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


// call the function...
loadScript(pathtoscript, function() {
  alert('script ready!'); 
});

If you're reading this post in 2021, probably you're more used to Promises. A more modern approach is preferable if either all your target browsers support ES6 or you are using a polyfill.

This solution works like @JaykeshPatel answer, but it's based on Promises:

// definition
function loadScript(scriptUrl) {
  const script = document.createElement('script');
  script.src = scriptUrl;
  document.body.appendChild(script);
  
  return new Promise((res, rej) => {
    script.onload = function() {
      res();
    }
    script.onerror = function () {
      rej();
    }
  });
}

// use
loadScript('http://your-cdn/jquery.js')
  .then(() => {
    console.log('Script loaded!');
  })
  .catch(() => {
    console.error('Script loading failed! Handle this error');
  });

You can pass some contextual variables in arguments of the res callback, or if your library imported some global symbol, you can reference it there.

For example, since jQuery introduces the $ global symbol, you can call res($) and create a local scope for it (perfect if you are using TypeScript and you don't want to declare a module variable in each file, in this way you can write const $ = await loadScript(..)).

If you don't mean to pass any argument, you can just shorten your code like this:

script.onload = res;
script.onerror = rej;

I had the same problem... My solution (without jQuery) :

<script onload="loadedContent();" src ="/myapp/myCode.js"  ></script>