Introduction to the
Dynamic loading of JS and CSS is definitely important now and in the future. At present, front-end code writing is far more business than back-end writing. As user experience increases, front-end services are complex and the loading speed becomes slow. To solve this problem, the two front-end module loaders that have emerged so far are require.js and sea.js, both of which are good. However, sometimes all I need is to load a JS dynamically without modularizing the code, so we have to write a loading function by hand.
Simple loading js
/ ** * HTML dynamic load js * @path {String} SRC address must have the suffix.js ** /
function addJs(path){
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script'); script.src=path; script.type= 'text/javascript'; head.appendChild(script); }Copy the code
This code has met our needs, dynamic loading JS. Then there’s the problem of assuming that some front end guy doesn’t know if you’ve loaded it or not, and loads it again, which is a waste of traffic, time, and possibly some kind of problem. Now let me optimize it.
Second best loading JS
/ ** * HTML dynamic load js * @path {String} SRC address must have the suffix.js ** /
var cache=[];
function addJs(path){
var flag=0;//Check the loading status
for(vari=cache.length; i--;) { cache[i]==path? flag=1:flag=0; }if(flag){//If it has been loaded, it is not loaded
return; }var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script'); script.src=path; script.type= 'text/javascript'; head.appendChild(script); cache.push(path);//Save what's loaded
}Copy the code
One day, there is a bug on the line again, the result is that it is caused by dynamic loading js, because only the js file is loaded, because the js file is too large, so it has not been successfully loaded, so it starts to use below. I’m going to improve it.
Nice loading js
/ ** * HTML dynamic load js * @path {String} SRC address must have a suffix* /
var cache=[];
function addJs(path,callback){
var flag=0;//Check the loading status
for(vari=cache.length; i--;) { cache[i]==path? flag=1:flag=0; }if(flag){//If it has been loaded, it is not loaded
return; }var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script'); script.src=path; script.type= 'text/javascript'; head.appendChild(script); script.onload= script.onreadystatechange = function() {/ *Check whether the load is successful* /
if (!this.readyState || this.readyState === "loaded" || this.readyState === "complete") { script.onload= script.onreadystatechange = null; callback(); }}; cache.push(path);//Save what's loaded
}Copy the code
It can be seen that now a little more perfect, one day the technical director said, the home page loading is too slow, JS, CSS to load dynamically. Now we need to change the code and optimize it again.
Recommended use of dynamic loading JS, CSS
var addStyleJs = (function(dom) {
var cache = {}, / *Caches loaded CSS or JS files* /
funct;
/ ** * HTML dynamic loading CSS or js * @path {String} SRC or link address must have the suffix.js or.css * @callback {Function} successfully loaded callback Function ** /
funct = function(path, callback) {
if(! path) {/ *Check whether the path is empty* /
throw newError(" Please enter path path!"); };varfn=Object.prototype.toString.call(callback)=="[object Function]"? callback:function() {};if(".js" == path.substr(-3)) { / *Check whether the path suffix is.js* /addJs(path, fn); }else if(".css" == path.substr(-4)) { / *Check whether the path extension is.css* /addCss(path, fn); }else {
throw newError(' Please enter the correct path path! '); }};/ ** * HTML dynamically added CSS * @path {String} Link address must have a suffix. CSS * @callback {Function} Successfully loaded callback Function ** /
function addCss(path, callback) {
if(! checkcache(path)) {/ *Check whether it has been loaded* /
var head = dom.getElementsByTagName('head')[0];
var link = dom.createElement('link'); link.href=path; link.rel= 'stylesheet'; link.type= 'text/css'; head.appendChild(link);/ *Add to HTML* /
link.onload = link.onreadystatechange = function() { / *Check whether the load is successful* /
if(!this.readyState || this.readyState === "loaded" || this.readyState === "complete") { link.onload= link.onreadystatechange = null; callback(); }}; cache[path]= 1; / *Store the loaded CSS path with the value set to 1* /}};/ ** * HTML dynamic load js * @path {String} SRC address must have a suffix* /
function addJs(path, callback) {
if(! checkcache(path)) {/ *Check whether it has been loaded* /
var head = dom.getElementsByTagName('head')[0];
var script = dom.createElement('script'); script.src=path; script.type= 'text/javascript'; head.appendChild(script);/ *Add to HTML* /
script.onload = script.onreadystatechange = function() { / *Check whether the load is successful* /
if(!this.readyState || this.readyState === "loaded" || this.readyState === "complete") { script.onload= script.onreadystatechange = null; callback(); }}; cache[path]= 1; / *Store the loaded JS path with a value of 1* /}};/ ** * Check if * @path {String} path * is loaded* /
function checkcache(path) {
if(cache[path]) { / *Check whether the js path has been loaded* /
return true; }else {
return false; }};return funct;
}(document));Copy the code
conclusion
Dynamic loading of JS and CSS may not be common in daily development, but it is a must for us. Code may take a few days to learn, but writing high-quality code requires a lot of writing, summarizing, and thinking. Welcome to progress with me. If you have a problem please point out oh!
Tip author channel ↓↓↓
If you think this article is good! Click on the recommendation to support oh!!
Pay attention to my
Collect the paper
Publish and subscribe
» Next up:
Command mode