# 代码
create-static-resource.js
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && (define.amd || define.cmd) ? define(factory) :
global.CSRE = factory();
}(this, function () {
'use strict';
var CODES = {
1: 'This paths is not an array'
}
function CSRE(opts) {
this.opts = opts;
this.createStaticElements(function () {
opts.loadend && opts.loadend();
})
}
var fn = CSRE.prototype;
fn.createStaticElements = function (callback) {
if (!this.opts.paths || !this.opts.paths instanceof Array) {
callback({
code: 1,
msg: CODES[1]
});
return;
}
var _this = this;
var len = this.opts.paths.length;
var count = 0;
for (var i = 0; i < len; i++) {
var val = this.opts.paths[i];
if (/\w+\.js/.test(val)) {
this.createScriptElement(val, loadEnd, loadError);
}
if (/\w+\.css/.test(val)) {
this.createLinkElement(val, loadEnd, loadError);
}
}
function loadEnd(el) {
count++;
if (count === len) callback();
}
function loadError(el) {
_this.opts.error && _this.opts.error(el);
count++;
if (count === len) callback();
}
}
fn.createScriptElement = function (src, loadend, loadErr) {
var el = this.opts.scriptInsert || 'body';
var script = document.createElement('script');
if (script.addEventListener) {
script.addEventListener("load", function (e) {
loadend(this);
}, false);
script.addEventListener("error", function (e) {
loadErr(this);
}, false);
} else if (script.attachEvent) {
script.attachEvent("onreadystatechange", function () {
var target = window.event.srcElement;
if (target.readyState === "loaded" || target.readyState === "complete") {
loadend.call(target);
} else {
loadErr.call(target);
}
});
}
if (window.jQuery) {
jQuery(el).append(script);
} else {
document.querySelector(el).appendChild(script);
}
script.src = src;
}
fn.createLinkElement = function (href, loadend, loadErr) {
var el = this.opts.linkInsert || 'head';
var link = document.createElement('link');
link.href = href;
link.setAttribute('rel', 'stylesheet');
link.setAttribute('type', 'text/css');
if (window.jQuery) {
jQuery(el).append(link);
} else {
document.querySelector(el).appendChild(link);
}
link.onload = function () {
loadend(this);
}
link.onerror = function () {
loadErr(this);
}
}
return CSRE;
}));
# 使用
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Create Static Resource Element</title>
</head>
<body>
<div id="app">
<h1>DEMO</h1>
<div>Create Static Resource Element</div>
</div>
<script src="create-static-resource.js"></script>
<script>
var Csre = new CSRE({
paths: [
'https://www.baidu.com/css/common.201709251646.css',
'https://www.baidu.com/js/common.201709251646.js',
'https://www.baidu.com/js/plugins.201709251646.js'
],
loadend: function () {
},
error: function (errElement) {
},
linkInsert: 'head',
scriptInsert: 'body'
});
</script>
</body>
</html>