js引入css/js文件
文章描述:
使用js载入css、js文件
方法一:
//引入css
var head = document.getElementsByTagName('head')[0];
var link = document.createElement('link');
link.href = 'css/app.css';
link.rel = 'stylesheet';
link.type = 'text/css';
head.appendChild(link);
//引入js
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.src = 'js/app.js';
script.type = 'text/javascript';
head.appendChild(script);
方法二:
在body里
//引入css
new_element=document.createElement("link");
new_element.setAttribute("rel","stylesheet");
new_element.setAttribute("type","text/css");
new_element.setAttribute("href","css/pc.css");
document.body.appendChild(new_element);
//引入js
new_element=document.createElement("script");
new_element.setAttribute("type","text/javascript");
new_element.setAttribute("src","js/pc.js");
document.body.appendChild(new_element);
方法三:
var importCssJs = {
css: function(path) {
if(!path || path.length === 0) {
throw new Error('参数"path"错误');
}
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('参数"path"错误');
}
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.src = path;
script.type = 'text/javascript';
head.appendChild(script);
}
}
//引用方法
importCssJs.css('css/m.css');
importCssJs.js('js/m.js');
发布时间:2021/12/29
发表评论