AMD and CMD-based module development and on-demand loading have brought convenience to our development process.
Today to share a project in the development of an on-demand loading JS method, not much, direct PS code
/** * JS loading to the top * @param {String} URL * @param {boolean} request and Load * @param {Function} fn * @return {Boolean} */function re Quirejs (URL, multi, fn) {if (typeof multi = = ' function ') {var _temp = fn; fn = multi; Multi = _temp; } var ss = document.getElementsByTagName (' script '); var loaded = false; for (var i = 0; I<SS. length; i++) {if (ss[i].src && ss[i].getattribute (' src ')== URL) {Loaded= true; Break ; }} if (loaded) {if (fn && typeof fn!)= ' undefined '&& fn instanceof Function) {fn (); return false; }} var s= document.createelement (' script '),b= false; s.setattribute (' type ', ' text/javascript '); if (multi) {This.loadjs= fn; var noarg= Url.indexof ('? ') = =-1; S.setattribute (' src ', url + (noarg? '? ': ' & ') + ' callback=wysiwyg.loadjs '); } else {s.setattribute (' src ', url); S.onload= S.onreadystatechange = function() {if (!b && (!this.readystate | | this.readystate== ' Loaded ' | | this.readystate== ' complete ')) {b= true; if (fn && typeof fn! )= ' undefined '&& fn instanceof Function) fn (); } }; } document.getelementsbytagname (' head ') [0].appendchild (s);}
This method will check whether the page has introduced the need to introduce JS, if not, then load the JS, if already exist, do not load;
Implementation of dynamic addition of JS file