首页 > 代码库 > 动态加载 移除js file

动态加载 移除js file

动态加载、移除、替换js/css文件stylesheetjavascriptcssfunctionnull <script language="javascript">//动态加载一个js/css文件function loadjscssfile(filename, filetype){if (filetype=="js"){var fileref=document.createElement(‘script‘)fileref.setAttribute("type","text/javascript")fileref.setAttribute("src", filename)}else if (filetype=="css"){var fileref=document.createElement("link")fileref.setAttribute("rel", "stylesheet")fileref.setAttribute("type", "text/css")fileref.setAttribute("href", filename)}if (typeof fileref!="undefined")document.getElementsByTagName("head")[0].appendChild(fileref)}</script>使用示例:loadjscssfile("myscript.js", "js")loadjscssfile("javascript.php", "js")loadjscssfile("mystyle.css", "css")<script language="javascript">//移动已经加载过的js/cssfunction removejscssfile(filename, filetype){var targetelement=(filetype=="js")? "script" : (filetype=="css")? "link" : "none"var targetattr=(filetype=="js")? "src" : (filetype=="css")? "href" : "none"var allsuspects=document.getElementsByTagName(targetelement)for (var i=allsuspects.length; i>=0; i--){if (allsuspects[i] && allsuspects[i].getAttribute(targetattr)!=null && allsuspects[i].getAttribute(targetattr).indexOf(filename)!=-1)   allsuspects[i].parentNode.removeChild(allsuspects[i])}}</script>使用示例:removejscssfile("somescript.js", "js")removejscssfile("somestyle.css", "css")替换已经加载的js/css文件,代码如下:<script language="javascript">function createjscssfile(filename, filetype){if (filetype=="js"){var fileref=document.createElement(‘script‘)fileref.setAttribute("type","text/javascript")fileref.setAttribute("src", filename)}else if (filetype=="css"){var fileref=document.createElement("link")fileref.setAttribute("rel", "stylesheet")fileref.setAttribute("type", "text/css")fileref.setAttribute("href", filename)}return fileref}function replacejscssfile(oldfilename, newfilename, filetype){var targetelement=(filetype=="js")? "script" : (filetype=="css")? "link" : "none"var targetattr=(filetype=="js")? "src" : (filetype=="css")? "href" : "none"var allsuspects=document.getElementsByTagName(targetelement)for (var i=allsuspects.length; i>=0; i--){if (allsuspects[i] && allsuspects[i].getAttribute(targetattr)!=null && allsuspects[i].getAttribute(targetattr).indexOf(oldfilename)!=-1){   var newelement=createjscssfile(newfilename, filetype)   allsuspects[i].parentNode.replaceChild(newelement, allsuspects[i])}}}</script>

 

动态加载 移除js file