JavaScript is nothing more than a script tag introduced into the page, but when the project is getting larger, the single page to introduce n JS obviously not, merged into a single file reduces the number of requests, but the requested file volume is very large. At this time the best way is to introduce, dynamically introduce component JS and style, file load completion call callback, run JS. The code is still very simple.
1. Judge the file load complete. Load state ie for onreadystatechange, others for onload, onerror
02 |
Res.onreadystatechange =function () { |
03 |
if (res.readystate = = ' Complete ' | | Res.readystate = = ' loaded ') { |
04 |
Res.onreadystatechange =null; |
06 |
_self.loadedui[modelname] =true; |
11 |
Res.onload =function () { |
14 |
_self.loadedui[modelname] =true; |
16 |
Res.onerror =function () { |
17 |
Thrownewerror (' res error: ' + modelname+ '. js '); |
2. The naming of all components is best kept consistent, and callback calls are also more convenient. You can also add parameters as needed: Requires, depending on those files; Style,true | | False, whether to load styles, and so on.
3. The removal operation can also have, remove script, style label, delete component
001 |
(function (window,undefined) { |
005 |
Dynamically loading the UI's JS |
008 |
Version:window.config.version, |
009 |
CssPath:window.config.resServer + '/css/v3/ui ', |
010 |
JsPath:window.config.resServer + '/js/v2/ui ' |
013 |
Readystatechange:function () { |
014 |
Varua = Navigator.userAgent.toLowerCase (); |
015 |
Returnua.indexof (' msie ') >= 0; |
017 |
Loadres:function (Modelname,prames,callback) { |
019 |
Varres = Document.createelement (prames.tagname); |
020 |
for (Varkin prames) { |
021 |
if (k!= ' TagName ') { |
022 |
Res.setattribute (k,prames[k],0); |
025 |
document.getElementsByTagName (' head ') [0].appendchild (Res); |
12V |
if (This.readystatechange ()) { |
028 |
Res.onreadystatechange =function () { |
029 |
if (res.readystate = = ' Complete ' | | Res.readystate = = ' loaded ') { |
030 |
Res.onreadystatechange =null; |
032 |
_self.loadedui[modelname] =true; |
036 |
Res.onload =function () { |
039 |
_self.loadedui[modelname] =true; |
041 |
Res.onerror =function () { |
042 |
Thrownewerror (' res error: ' + modelname+ '. js '); |
046 |
Removeui:function (modelname) { |
050 |
This.loadedui[modelname] =false; |
052 |
Varhead = document.getElementsByTagName (' head ') [0]; |
053 |
Varmodel_js = document.getElementById (' j_model_ ' +modelname + ' _js '); |
054 |
Varmodel_css = document.getElementById (' j_model_ ' +modelname + ' _css '); |
055 |
if (Model_js && model_css) { |
056 |
Deletewindow.ui[modelname]; |
057 |
Head.removechild (MODEL_JS); |
058 |
Head.removechild (MODEL_CSS); |