Caricare più files javascript o css in modo asincrono

ATTENZIONE! Il post ha più di 2 anni e le informazioni contenute potrebbero essere obsolete (ad esempio a causa di un aggiornamento di versione rispetto agli elementi descritti o links modificati da siti esterni).

Da una richiesta fatta in un commento del post "Caricare un file JavaScript o CSS in modo asincrono" ho sviluppato una nuova funzione per caricare più files in modo asincrono e impostare una funzione di callback alla fine del caricamento di tutti i files.

Lo script:

function loadAsyncMultiple(items, callback) {
 this.items = items;
 this.callback = callback;
 this.loaded_items_counter = 0;
 this.items_length = 0;
 this.items_loaders = new Array();
 //inizializza
 this.loadAll = function () {
  //numero di elementi da caricare
  this.items_length = this.items.length;
  //cicla elementi
  for (var i = 0; i < this.items_length; i++) {
   this.loadScript(i, this.items[i].url, this.items[i].type);
  }
 };
 //caricamento singolo elemento
 this.loadScript = function (i, url, type) {
  var tis = this;
  this.items_loaders[i] = {r: false, s: {}};
  switch (type) {
   case 'css':
    this.items_loaders[i].s = document.createElement('link');
    this.items_loaders[i].s.rel = 'stylesheet';
    this.items_loaders[i].s.type = 'text/css';
    this.items_loaders[i].s.href = url;
    break;
   case 'js':
    this.items_loaders[i].s = document.createElement('script');
    this.items_loaders[i].s.type = 'text/javascript';
    this.items_loaders[i].s.src = url;
    break;
  }
  this.items_loaders[i].s.async = true;
  this.items_loaders[i].s.onload = this.items_loaders[i].s.onreadystatechange = function () {
   if (!tis.items_loaders[i].r && (!this.readyState || this.readyState === 'complete')) {
    tis.items_loaders[i].r = true;
    tis.incrementCounter();
   }
  };
  document.getElementsByTagName('head')[0].appendChild(this.items_loaders[i].s);
 };
 //counter
 this.incrementCounter = function () {
  this.loaded_items_counter++;
  //quando tutti gli elementi sono stati caricati
  if (this.loaded_items_counter === this.items_length) {
   //se è stata definita una funzione di callback
   if (this.callback && typeof this.callback === "function") {
    this.callback();
   }
  }
 };
};

Lo script accetta 2 parametri: un array con gli elementi da caricare (sia js che css) e una funzione di callback da richiamare alla fine del caricamento.

Ecco un esempio di utilizzo:

//elementi da caricare
var items = [
 {'type': 'css', 'url': 'demo1.css'},
 {'type': 'js', 'url': 'demo1.js'},
 {'type': 'js', 'url': 'demo2.js'},
 {'type': 'js', 'url': 'demo3.js'}
];

//funzione da eseguire alla fine del caricamento
var callback_func = function () {
 alert('Tutti gli script sono stati caricati!');
};

//inizializzazione loader
var loader = new loadAsyncMultiple(items, callback_func);
loader.loadAll();

 

 


Commenti