3

yesterday I saw that there are not many examples of js autoloader, and most of them are written by using jquery,so I wrote the one with plain js and loading it's loading libraries synchronously.

Also, here is the link to github repo : simple-js-libraries-autoloader

/**
 * 
 * JavaScript libraries autoloader 
 * @author Aleksandr Cerkasov <coldworld333@gmail.com>
 * 
 */


// writing the window.onload scope, because the libraries should be added when
// document is fully loaded
window.onload = function () {
    // defining libraries to load
    var jsScripts = [
        'components/ajaxRequest.js',
        'config/main.js',
        'config/router.js'
    ];

    // getting <head> element to append the libraries to
    var htmlHead = document.getElementsByTagName('head')[0];

    // scriptElement is array because we need the library to be loaded maybe even later
    var scriptElement = [];

    for (var key in jsScripts) {
        // creating <script> element
        scriptElement[key] = document.createElement('script');

        // setting the <script> element's type
        scriptElement[key].type = 'text/javascript';

        // setting the <script> element's source
        scriptElement[key].src = jsScripts[key];

        // making it synchronous
        scriptElement[key].async = false;

        // appending the <script> element to the <head> element
        htmlHead.appendChild(scriptElement[key]);
    }
}

I hope this will be useful for somebody.

Aleksandr Sasha
  • 168
  • 1
  • 12
  • Why did you _prefer_ `for..in` over `for-loop` ? – Rayon Jun 17 '16 at 07:55
  • 1
    Whichever language you are using is not common for many of users! Do communicate in __English__ – Rayon Jun 17 '16 at 07:56
  • Rayon >> well, it could be written by using for (var i = 0; i < jsScripts.length; i++) but at this point I prefer to use for in – Aleksandr Sasha Jun 17 '16 at 07:58
  • But SO is a questions service. Not code snippets. – Constantine Jun 17 '16 at 07:59
  • @AleksandrSasha, Well, Refer [__JavaScript for…in vs for__](http://stackoverflow.com/questions/242841/javascript-for-in-vs-for) – Rayon Jun 17 '16 at 08:00
  • Constantine >> yes, but yesterday I was looking for something like this, and really did not found the ones which would fit my needs, that's why I decided to write the one and publish – Aleksandr Sasha Jun 17 '16 at 08:01
  • Rayon >> actually, yes, there is a difference between for in and for, but at this point both of them can be used. But, the better way is ofcourse to for() without "in", I am mostly working with php, and really know the difference between for and for in, foreach as in php can be used like a simple for, but it just takes more resources, and is designed for a simplier way to search in object – Aleksandr Sasha Jun 17 '16 at 08:10
  • Rayon >> whatever language you are used to, the google-translate plugin isn't that hard to install and learn to use. – Scott Oct 05 '17 at 15:46

0 Answers0