[英]Reload JavaScript files without refreshing HTML
I've a HTML which loads several Javascript files: 我有一个加载几个Javascript文件的HTML:
<script src="assets/js/a.js"></script>
<script src="assets/js/b.js"></script>
<script src="assets/js/jquery.min.js"></script>
As I debug/test my Javascripts in my browser's console, is it possible to reload these Javascript files without the need to reload the entire HTML page? 当我在浏览器的控制台中调试/测试我的Javascripts时,是否可以重新加载这些Javascript文件而无需重新加载整个HTML页面?
You could remove and then re-add them: 您可以删除然后重新添加它们:
$('script').each(function() {
if ($(this).attr('src') !== 'assets/js/jquery.min.js') {
var old_src = $(this).attr('src');
$(this).attr('src', '');
setTimeout(function(){ $(this).attr('src', old_src + '?'+new Date()); }, 250);
}
});
Nope (at least not without a hack), in fact - be very careful reloading so much. 事实上,没有(至少不是没有黑客) - 非常小心地重装。 It's quite possible that your javascripts become cached, which leads to many-a-headache trying to debug, since your updates are not applying.
您的javascripts很可能会被缓存,这会导致尝试调试时出现很多麻烦,因为您的更新不适用。
https://superuser.com/questions/36106/force-refreshing-only-javascript-files-in-firefox-and-chrome https://superuser.com/questions/36106/force-refreshing-only-javascript-files-in-firefox-and-chrome
Tested with jQuery 2.0.3 and chrome 43 使用jQuery 2.0.3和chrome 43进行测试
function reloadScript(id) {
var $el = $('#' + id);
$('#' + id).replaceWith('<script id="' + id + '" src="' + $el.prop('src') + '"><\/script>');
}
Chrome is complaining, but works: Chrome正在抱怨,但有效:
Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. 主线程上的同步XMLHttpRequest因其对最终用户体验的不利影响而被弃用。 For more help, check http://xhr.spec.whatwg.org/ .
如需更多帮助,请访问http://xhr.spec.whatwg.org/ 。
Your script tag has to have id. 您的脚本标记必须具有ID。 Call in console:
在控制台中呼叫:
reloadScript('yourid');
Does not remove event listeners, so for for example button click gets executed twice if once reloaded. 不删除事件侦听器,因此例如,如果重新加载,则按钮单击将执行两次。
Based on PitaJ's solution. 基于PitaJ的解决方案。
Reload all javascript in a function. 重新加载函数中的所有javascript。 You can call this from anywhere you want.
你可以从任何你想要的地方打电话。
$('script').each(function () {
if ($(this).attr('src') != undefined && $(this).attr('src').lastIndexOf('jquery') == -1) {
var old_src = $(this).attr('src');
var that = $(this);
$(this).attr('src', '');
setTimeout(function () {
that.attr('src', old_src + '?' + new Date().getTime());
}, 250);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.