jQuery的:如何插入或删除运行.js文件? [英] jQuery: How to insert or remove a .js file at runtime?

查看:141
本文介绍了jQuery的:如何插入或删除运行.js文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想添加一个.js文件的链接被点击之后。
该.js文件是一个脚本,不具有的功能直接调用,但该文件已在网站的主体部分插入。

另一个解决方案是,如果文件被称为在页面加载,如果链接的点击事件被称为,然后取出.js文件。

我已经试过这样的事情,但没有任何反应:

  $(。myLink的)。点击(函数(){
    $ .getScript(myJavascriptFile.js);
});

和也在这里:

  $(。myLink的)。点击(函数(){
VAR脚本=使用document.createElement('脚本');
        script.type =文/ JavaScript的';
        script.src =app_javascript / dragscroll.js
        $(myDiv)附加(脚本)。 //或$(机构)追加(脚本)。
});


解决方案

嗯,其实,什么也没发生的声音最有可能过大。
getScript加入是通过各种手段异步的,所以你应该提供任何code,它依赖于负载的处理程序,这实际上是,第二个参数使用该脚本。

$。getScript加入('here_comes_the_script.js',函数(){... //这里来了code})

您可以使用一些包装,使事情更加灵活 - 通过将事件处理程序加载,这样的事情:

  getScriptDetectable =功能(SRC){
     getScript加入(SRC,函数(){
      (文档)$ .trigger(new_script,{SRC:SRC})
     });
}

但是,这当然不会从考虑的事实,这code是异步的释放你。

和有关删除脚本。居然还有就是让浏览器unsee的code没有通用的方法。

您可以试着这样做:

 变种SRC = document.querySelector('脚本');
src.parentNode.removeChild(SRC);

但在这个文件中的所有code这已经被评估进行评估,所以没有太大的意义在于此。

i want to add a .js file after a link has been clicked. The .js file is a script, that has no function to call directly, but the file has to be inserted in the body part of the site.

Another solution would be, if the file is called at page load and if the click event of the link is called, then remove the .js file.

I've tried something like this, but nothing happens:

$(".myLink").click(function(){
    $.getScript("myJavascriptFile.js");
});

and also here:

$(".myLink").click(function(){
var script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = "app_javascript/dragscroll.js";
        $(".myDiv").append(script); // or  $("body").append(script);
});

解决方案

Well, actually, "nothing happens" sounds most probably too loud. getScript is by all means asynchronous, so you should provide any code, which relies on using this script in load handler, which is actually, the second param.

$.getScript('here_comes_the_script.js', function(){...//here comes the code})

You can use some wrapping to make thing more flexible - by passing events to load handler, something like this:

getScriptDetectable = function(src) {
     getScript(src, function() {
      $(document).trigger("new_script", {src: src})
     });
}

But this, of course, doesn't free you from considering the fact that this code is asynchronous.

And about removing script. There is actually no general way to make browser "unsee" the code.

You can try do something like:

var src = document.querySelector('script');
src.parentNode.removeChild(src);

but all code in this file which has been evaluated already is evaluated, so there is no much sense in this.

这篇关于jQuery的:如何插入或删除运行.js文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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