使用jquery替换脚本src未执行 [英] Replacing script src using jquery not executed
问题描述
这是我所做的。
.... ..............
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只是为了限制替换范围
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;
});
});
......................
在Firebug中,目标旧的src url(/old_path_to_file.js)被替换为新的(/new_path_to_file.js)。所以更换工作。但是它报告,(请参阅真正的绝对url http://,如果相关):
无法加载源: http://localhost/........js
所以脚本src被替换,但不执行。任何我错过的东西,如果这个东西是允许的?
我也试图使用$ .getScript(absUrl + options.newVal +'.js');但是这不是替代旧的src,只是添加更多的js到dom,这不是我想要的。任何提示这个部分?
感谢所有可能的帮助。
你想替换旧的脚本吗?也就是说,装载了脚本标签的javascript不再在内存中,而是新的javascript?你不能这样做。您必须取消定义和解除原始脚本执行的事件。
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.
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.
这篇关于使用jquery替换脚本src未执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!