Reputation: 2599
I would like to replace the source url of the script on the fly to speed up dev stages only, so no actual production usage. This kind of replacement works well with css or images. But have hard time to make it work with javascript src. The script seems not executed, although loaded via src.
Here is what I have done.
..................
return this.each(function() {
$(this).click(function() {
var t = $(this);
options.newVal = t.val();
var absUrl = '/root_path_still_within_the_same_domain/';
//options.oldVal is just to limit the replacement scope
var oldJsUrl = absUrl + options.oldVal + '.js';
var newJsUrl = absUrl + options.newVal + '.js';
var reJsUrl = $('script[type*=javascript][src*=' + options.oldVal + ']' || 'script[type*=javascript][src*=' + options.newVal + ']');
if (oldJsUrl.length && options.oldVal.length) {
reJsUrl.attr('src', newJsUrl);
}
options.oldVal = options.newVal;
});
});
......................
In Firebug, the target old src url (/old_path_to_file.js) is replaced with the new one (/new_path_to_file.js). So the replacement works. But it reports, (see the real absolute url http://, in case relevant):
Failed to load source for: http://localhost/........js
So the script src is replaced, but not executed. Anything I missed, if this stuff is allowed anyway?
I have also tried to use $.getScript(absUrl + options.newVal + '.js');, but this is not replacing the old src, just adding more js to the dom, which is not what I want. Any hint on this part too?
Thanks for all possible help.
Upvotes: 2
Views: 1958
Reputation: 630637
If you just want to include another script:
var script = document.createElement("script");
script.src = url; //Specify url here
script.type = "text/javascript";
$("body").append(script);
This will add a script and execute it...you can't replace the src
and have it run for security reasons. You also can't just "undo" anything the original script did...based on your question I don't think that's an issue, but if it is, maybe you should not include the initial script tag, decide what you need and dynamically create the script element like I showed above.
Upvotes: 2
Reputation: 70528
Do you want to "replace" the old script? That is to say, the javascript that was loaded with the script tag is no longer in memory and the new javascript is? You can't do this in this way. You have to un-define and unattach event preformed by the original scripts.
Upvotes: 0