JS 实现需要时加载js和css文件_html/css_WEB-ITnose

WBOY
Release: 2016-06-21 08:53:36
Original
1174 people have browsed it

当我做前端开发时,我们会经常遇到这样的情况:我可能需要引入一些包做一些特殊的事情,可是这个包在部分的情况是用不到的。所以我们就希望在需要的时候再加载这个包。下面提供一个比较好的方法,用来动态加载这个js 和css文件

function $import(path,type,title){ var s,i; if(!type) type=path.substr(path.lastIndexOf(".")+1); if(type=="js"){ var ss=document.getElementsByTagName("script"); for(i=0;i<ss.length;i++){     if(ss[i].src && ss[i].src.indexOf(path)!=-1 ||        ss[i].title==title)return ss[i]; } s=document.createElement("script"); s.type="text/javascript"; s.src=path; if(title) s.title=title; }else if(type=="css"){ var ls=document.getElementsByTagName("link"); for(i=0;i<ls.length;i++){     if(ls[i].href && ls[i].href.indexOf(path)!=-1 || ls[i].title==title)return ls[i]; } s=document.createElement("link"); s.rel="stylesheet"; s.type="text/css"; s.href=path; if(title) s.title=title; s.disabled=false; } else return; var head=document.getElementsByTagName("head")[0]; head.appendChild(s); return s; }
Copy after login

你只需要在调这个方法时,传入文件路径和文件类型(js, css)。这样就会在

标签里加包的导入
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template