Recently because the work needs to do a JS auto-import plug-in, a very naïve to start with the dynamic creation of a script added to the head is OK, after trying to find the problem, that is, if the introduction of a number of JS files, and the latter a file used in the previous file variables, it will error, rely on ~ ~ Sad urge, that is, JS if dynamic loading (non-browser loading because the browser load synchronization will wait for the previous JS loading completed before the next JS load, so that there is no problem) the loaded file is asynchronous, no wonder Ah! And then find some information on the Internet to use Ajax synchronous loading, and then I try to really, the following is my code to share out to everyone, but note that such a loaded JS has a fatal weakness, is unable to debug on the browser-!!!!! Find a solution later, put the code first:
JS main file Importcomjs.js:
* * Created by Carlos on 2015/5/19. * Qimport Import Help function, it is convenient to import the specified JS, CSS files. However, it should be noted that such imported JS will be unable to debug, temporarily found no solution--! * Use the method to first introduce this file, must be placed in the head in front of the import, * <script src= ". /js/importcomjs.js "id=" Qimport "></script> * ID must be qimport, otherwise invalid * then join * <script> * QIMPORT.INIT ( customscripts); * </script> * customscripts parameter: Plus the introduction of file configuration, you can not fill. But fill in must obey Qimport.importscripts's writing. * If you do not want to initialize the introduction function manually, you can write: * <script src= ". /js/importcomjs.js "id=" Qimport "data-auto=" true "></script> * This is true when the Data-auto is automatically initialized, otherwise it needs to be initialized manually. * Use on automatic initialization, do not worry about the introduction of order problems, the following other JS, CSS files according to normal reference. * Note: The Importcomjs file must be first introduced, otherwise there will be a problem that the reference could not be found. * Added Properties: * Data-config: Custom profile name, default to "Importconfig.json" * data-personalconfigname: Custom personalization name, "personalscripts" in config file In configuration * Note: The configuration load order is: Importscripts highest, personalscripts second, customscripts lowest. If the introduction of the wrong order will cause a null pointer error oh ^^! *//** * Synchronous Loading JS script * @param ID needs to set the ID of the <script> tag * @param the relative path of the URL js file or the absolute path * @return {Boolean} returns whether the load succeeded, true generation Table succeeded, false represents failure */(function () {Qimport = {self:{obj:function () {return document.getElementById (' Qimport '); Get the script ID, if there is a conflict in the project has to change, then this "Qimport" it! },auto:function () {return eval (this.getattr (' Data-auto ')); Whether to turn on automatic initialization mode, default to False},config:function () {return this.getattr (' Data-config '); Custom profile name, default to "Importconfig.json"},personal:function () {return this.getattr (' data-personalconfigname ')// Customize the personalization configuration name, which is configured in "Personalscripts" in the configuration file. },src:function () {return this.getattr (' src '); This file location, not much said},getattr:function (attrname) {var attrValue = Undefined;try{attrvalue = This.obj (). getattribute (Attrname) ;} catch (e) {}return attrvalue;},relationpath:function () {var src = this.src (); var re =/^[: \/]*/;return Src.match (re) [0];},path:function (filename) {var src = this.src (); var temp = Src.split ('/'); var path = ""; Temp.pop (); Temp.push (filename), return temp.join ('/'),}},autoinit:function () {if (This.self.auto ()) {This.init ()}} , Getpath:function (p) {var path = This.self.relationpath () +p;return path.replace ('//', '/');},init:function ( Customscripts{//import file Main method This.extend (customscripts); var importscripts = this. Importscripts;var head = document.getElementsByTagName ("Head"). Item (0); var meta = document.createelement (' meta '); Automatically add a web phone adaptation code; meta.name = ' viewport '; meta.content = ' width=device-width,initial-scale=1,minimum-scale=1, Maximum-scale=1,user-scalable=no '; Head.insertbefore (meta, head.childnodes[0]); var re =/^http[s]?:\ /\//i;for (var i=0;i<importscripts.length;i++) {LoadPath = Importscripts[i].url; if (!re.test (IMPORTSCRIPTS[i].url ) {LoadPath = This.getpath (Importscripts[i].url);} if (importscripts[i].type== "script") {var flag = This.loadjs (loadpath,loadpath,i+1) if (!flag) {alert (' Loading path: ' + loadpath+ ' "Failed,may be Lost" http (s)://"');}} else if (importscripts[i].type== "CSS") {var csss = document.createelement (' link ') csss.href = This.getpath ( Importscripts[i].url); Csss.rel = ' stylesheet '; Head.insertbefore (Csss, head.childnodes[i+1]); }}},extend:function (customscripts) {//Custom extension method, only applicable to current object if (! ( CusTomscripts instanceof Array) Return;var importscripts = this. Importscripts;for (var i=0;i<customscripts.length;i++) {var flag = False;for (Var j=0;j<importscripts.length;j++ ) {if ((Importscripts[j].type==customscripts[i].type) && (Importscripts[j].url==customscripts[i].url)) { flag = True;break;}} if (!flag) {this. Importscripts.push ({type:customscripts[i].type,url:customscripts[i].url});}}},ajax:function (URL) { The Ajax primitive method, where only the synchronous request var xmlHttp = null can be requested; if (window. ActiveXObject)//ie {try {//ie6 and later versions can use XmlHttp = new ActiveXObject ("Msxml2.xmlhttp"); } catch (e) {//ie5.5 and later versions can use XmlHttp = new ActiveXObject ("Microsoft.XMLHTTP"); }} else if (window. XMLHttpRequest)//firefox,opera 8.0+,safari,chrome {xmlHttp = new XMLHttpRequest (); }//Using synchronous loading Xmlhttp.open ("GET", Url,false); Send a sync request, if the browser is Chrome or opera, must be published to run, or will be error xmlhttp.send (NULL); //4 means that the data is sent if (xmlhttp.readystate = = 4) {//0 is accessed locally, 200 to 300 represents the access server succeeds, 304 means that no modifications are accessed by the cache if (Xmlhttp.status & gt;= && xmlhttp.status <300) | | Xmlhttp.status = = 0 | | Xmlhttp.status = = 304) {return xmlhttp.responsetext; } else{return false; }} else{return false; }},loadjs:function (Id,url,rank) {//Load js file var importtext = this.ajax (URL); if (!importtext) return false; var myhead = document.getElementsByTagName ("HEAD"). Item (0); var myScript = document.createelement ("script"); Myscript.language = "JavaScript"; Myscript.type = "Text/javascript"; Myscript.id = ID; try{//IE8 and the following do not support this way, you need to set the Text property to Myscript.appendchild (document.createTextNode (Importtext)); } catch (ex) {myscript.text = Importtext; } myhead.insertbefore (MyScript, Myhead.childnodes[rank]); Return true;},template:{//loads the template file and is now available only in the case of "jquery". parent:this,//Parent Class This reference _setparent:functIon () {///parentthis.template.parent = This;},includetagname: ' Include ',//tags used when introducing the parent class: <include url= " Head.html "></include>init:function () {this.include ();},include:function () {var includes = document.getElementsByTagName (This.includetagname); for (Var i=0;i<includes.length;i++) {var url = includes[i]. getattribute (' url '); var includehtml = This.parent.ajax (URL); var parent = Includes[i].parentnode;var Newes = This.parsedom (includehtml); for (Var j=0;j<newes.length;j++) {Parent.insertbefore (newes[j], includes[i])}}while ( True) {if (includes.length==0) Break;includes[0].remove ();}},parsedom:function (str) {var obj = document.createelement (' div '); obj.innerhtml = Str;return obj.childnodes;}}, Initparent:function () {///subclass the method in the parent class must be initialized by this method and must also introduce the Template's parent and _setparentthis.template._setparent.call (this);},getimportjson:function () {//Get configuration Jsonvar ConfigName = This.self.config (); Shared configuration if (configname) This.configname = Configname;var Configpath = This.self.path (This.configname); var confjsonstr = This.ajax (Configpath), if (!CONFJSONSTR) {alert (' Config file path: ' +configpath+ ' "Can not is loaded '); return;} This.confjson = eval (' (' +confjsonstr+ ') '); Importarr = this.confjson.importscripts;if (Importarr instanceof Array) { This. importscripts = this.confJson.importscripts;} This.getpersonalarr ();},getpersonalarr:function () {//Get personalized configuration Arrvar Personalconfigname = This.self.personal (); Personalconfigname) Return;this.personalconfigname = Personalconfigname;var Personalarr = This.confjson.personalscripts[personalconfigname];if (Personalarr instanceof Array) {this.extend (Personalarr)}}, Confjson:{},importscripts:[],configname: ' Importconfig.json '}qimport.getimportjson (); Qimport.autoinit (); Qimport.initparent (); try{$ (function () {QImport.template.init ();}); catch (e) {}}) ();
Here is the configuration file, Importconfig.json:
{importscripts:[{type: ' script ', url: ' js/jquery-1.9.1/jquery-1.9.1.min.js '},{type: ' script ', url: ' Js/mui.min.js '}, {type: ' css ', url: ' css/mui.min.css '},{type: ' script ', url: ' js/json2.js '}],personalscripts:{test:[{type: ' script ', URL: ' Js/test.js '}]}}
Note that the configuration file must be in the same path as the import method JS.
The above is my personal encapsulation of the introduction of JS, CSS code, I hope and we exchange, what is the problem I hope you can feel free!
JS plugin dynamic loading js, CSS Solution