Javascript - Module Loader (Script Loader)


A loader searches and loads module and script into the javascript engine (environment).

From the main script, they will:

They will generally load them recursively while building the dependency graph to gain speed



Browser: Basic Script Loader

The most generic of script loaders simply create a script tag element and inject it into the loaded page. Since the DOM element is injected, it logically cannot 'block' the rendering of the rest of the page so the browser treats it as if it were asynchronous. Asynchronous scripts don't block so you can load more than one at a time.

// Very simple asynchronous script-loader

// Create a new script element
var script      = document.createElement('script');

// Find an existing script element on the page (usually the one this code is in)
var firstScript = document.getElementsByTagName('script')[0];

// Set the location of the script
script.src      = "";

// Inject with insertBefore to avoid appendChild errors
firstScript.parentNode.insertBefore( script, firstScript );

// That's it!

Browser: Library


Node Native

In node, the require function is used directly as loader.

You can influence it via the NODE_PATH that may contain a list of path where module should be searched

Node Library

Node Snippet example

An example of a node loader

const lib = path.join(__dirname, '..', '..', 'lib')
if (fs.existsSync(lib)) {
  // Use the latest src
  module.exports.resolve = { alias: { 'library_name': lib } }
} else {
    throw "library source not built. Run the following: 'pushd ../.. && rm -rf node_modules && yarn install && yarn run build && popd' and then rerun 'yarn start'"


Node Loader monitors modify the code loaded dynamically.

Documentation / Reference

Powered by ComboStrap