Hardcoded Callback

Examples ▼
Was the script loaded without blocking?
Was execution order preserved?
 
 
 

This page contains an external script and some inlined code. The external script is loaded asynchronously (using the Script DOM Element technique). The inlined code's init function calls scriptAFunc, a function defined in the external script. Because of this dependency, the inlined code must be coupled with the external script so that the execution order is preserved: the external script is loaded, parsed, and executed before the inlined code.

In this example, the external script and inlined code are coupled using a hardcoded callback. The call to init is tacked on to the end of the external script. This is guaranteed to work, but is not very flexible. It requires that the developers of the main page and the external script integrate their code, something that's not possible when using 3rd party JavaScript modules.

inlined code in main page:   external script:
function init() {
  createMenu('examples');
}

var domscript = document.createElement('script');
domscript.src = "menu-with-init.js";
document.getElementsByTagName('head')[0].appendChild(domscript);
 
function createMenu(id) {
  [...]
}

// callback to the main page
init();