This example describes the asynchronous script loading method for JavaScript with callback functions. Share to everyone for your reference. The implementation methods are as follows:
var Loader = function () {}
Loader.prototype = {
require:function (scripts, callback) {
This.loadcount = 0;
this.totalrequired = scripts.length;
This.callback = callback;
for (var i = 0; i < scripts.length i++) {
this.writescript (scripts[i]);
}
,
loaded:function (evt ) {
this.loadcount++;
if (This.loadcount = = this.totalrequired && typeof this.callback = = ' function ') this.callback.call ();
},< C16/>writescript:function (src) {
var self = this;
var s = document.createelement (' script ');
S.type = "Text/javascript";
S.async = true;
S.SRC = src;
S.addeventlistener (' Load ', function (e) {self.loaded (e);}, false);
var head = document.getElementsByTagName (' head ') [0];
Head.appendchild (s);
}
Usage Demo
var L = new Loader ();
L.require ([
"Example-script-1.js",
"Example-script-2.js"],
function () {
//Callback
Console.log (' All Scripts Loaded ');
};
I hope this article will help you with your JavaScript programming.