Simple javascript files loader for embeddable javascript application


To develop a large scale javascript application, embeddable to pages, the first problem I faced was including large number of javascript files in the page. So like google or yahoo applications you simply include one javascript file and after few lines of javascript to start the application, otherwise you will end up with something like this:

You might have a simple, advanced and other versions of your application and the end user will have to figure out (or you have to explain) which files need to be included for different versions of applications. Also it looks ugly and meaningless for the enduser to include a big list of javascript files.

You can simply include all your javascripts in one big file and minify it, but

  • Sometime you want to keep your javascript libraries separate from your code
  • Also you might want to include different number of javascript files depend on which features user want to use. You will never want to load all javascript files if user want to embed just a simple/basic version of your javascript application.

Append script tags to head?

You might be thinking why don’t make an array of javascript files name, loop through this array and than for each file name, make a script tag and append it to the head tag. Well this is the solution but you might be loading external javascript files or host your javascript files outside on a CDN and some javascript files will load slower than others. Your javascript code might be depended on other javascript files, for example if you are loading jQuery library and than all your jQuery plugins, you might get an error “jQuery not defined” in your plugin files because jQuery might take longer to load than your plugins. So your plugins will load first and jQuery will still be loading so it will break your application.

jQuery’s getScript method can be used to load ONE javascript file at a time. You can use it inside a ‘for’ loop and use getScript’s callback to include the next script in an array of script file names. But you would never like to include a whole jQuery library just for this purpose (when you are not using jQuery anywhere else in your application).


My idea to embed javascript application is include a single javascript file. Call a function and pass the type of application as argument. The function should make a list of javascript files to include, depend of the type of application and once all js files are loaded, call a callback function. Something like:


Continue Reading →

Copyright © 2018 — musings of Aamir Afridi