在运行时加载和卸载javascript [英] Load and unload javascript at runtime

查看:104
本文介绍了在运行时加载和卸载javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在运行时通过JavaScript添加或删除JavaScript文件和CSS文件?如果JavaScript不可能,那么我们可以通过PHP或任何其他服务器站点语言来实现吗?

Is it possible to add or remove JavaScript files and CSS files by JavaScript at run time? If it's not possible by JavaScript then, Can we do it by PHP or any other server site language?

实际上我试过yep-nope js但是我无法通过它卸载任何javascript。

Actually i tried by yep-nope js but i am not able to unload any javascript by it.

推荐答案

检查这个这个这个

从顶部链接,动态添加js或css:

From the top link, to dynamically add js or css:

function loadjscssfile(filename, filetype){
 if (filetype=="js"){ //if filename is a external JavaScript file
  var fileref=document.createElement('script')
  fileref.setAttribute("type","text/javascript")
  fileref.setAttribute("src", filename)
 }
 else if (filetype=="css"){ //if filename is an external CSS file
  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)
}

loadjscssfile("myscript.js", "js") //dynamically load and add this .js file
loadjscssfile("javascript.php", "js") //dynamically load "javascript.php" as a JavaScript file
loadjscssfile("mystyle.css", "css") ////dynamically load and add this .css file

此外,要动态删除js或css:

Also, to dynamically remove js or css:

function removejscssfile(filename, filetype){
 var targetelement=(filetype=="js")? "script" : (filetype=="css")? "link" : "none" //determine element type to create nodelist from
 var targetattr=(filetype=="js")? "src" : (filetype=="css")? "href" : "none" //determine corresponding attribute to test for
 var allsuspects=document.getElementsByTagName(targetelement)
 for (var i=allsuspects.length; i>=0; i--){ //search backwards within nodelist for matching elements to remove
  if (allsuspects[i] && allsuspects[i].getAttribute(targetattr)!=null && allsuspects[i].getAttribute(targetattr).indexOf(filename)!=-1)
   allsuspects[i].parentNode.removeChild(allsuspects[i]) //remove element by calling parentNode.removeChild()
 }
}    
removejscssfile("somescript.js", "js") //remove all occurences of "somescript.js" on page
removejscssfile("somestyle.css", "css") //remove all occurences "somestyle.css" on page

但请注意删除:


那么删除外部JavaScript或CSS文件时会发生什么?也许并不完全是你所期望的。在
的JavaScript案例中,当元素从文档
树中删除时,作为外部JavaScript文件的一部分加载的任何代码在浏览器的内存中仍然是
。也就是说,您仍然可以访问外部文件首次加载
时添加的
变量,函数等

这篇关于在运行时加载和卸载javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆