用JavaScript动态加载CSS和JS文件

var dynamicLoading = {
    css: function (path) {
        if (!path || path.length === 0) {
            throw new Error('argument "path" is required !');
        }
        var head = document.getElementsByTagName('head')[0];
        var link = document.createElement('link');
        link.href = path;
        link.rel = 'stylesheet';
        link.type = 'text/css';
        head.appendChild(link);
    },
    js: function (path) {
        if (!path || path.length === 0) {
            throw new Error('argument "path" is required !');
        }
        var head = document.getElementsByTagName('head')[0];
        var script = document.createElement('script');
        script.src = path;
        script.type = 'text/javascript';
        head.appendChild(script);
    }
}

//动态加载 CSS 文件
dynamicLoading.css("css/test.css?v=201705027588797");
//动态加载 JS 文件
dynamicLoading.js("test.js");

JS判断是否有js、css文件的引入方法

function isInclude(name) {
	var js = /js$/.test(name);
	var es = document.getElementsByTagName(js ? 'script' : 'link');
	for (var i = 0; i < es.length; i++)
		if (es[i][js ? 'src' : 'href'].indexOf(name) != -1)return true;
	return false;
}
alert(isInclude("abc.js"));
alert(isInclude("efg.css"));

相关推荐