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:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24-25 |
var Loader = function () {} Loader.prototype = {require:function (scripts, callback) {this.loadcount = 0; this.totalre quired = 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 (); }, 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
?
1 2 3 4 5 6 7 8 |
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.