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:
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:
but all code in this file which has been evaluated already is evaluated, so there is no much sense in this.