问题描述
在.js文件上进行开发时,我只想刷新该文件而不是整个页面以节省时间。有人知道这方面的任何技术吗?
While doing development on a .js file I'd like to just refresh that file instead of the entire page to save time. Anyone know of any techniques for this?
推荐答案
这是一个创建新脚本元素的函数。它附加一个递增的整数,以使脚本的URL唯一(如Kon建议的那样)以强制下载。
Here is a function to create a new script element. It appends an incremented integer to make the URL of the script unique (as Kon suggested) in order to force a download.
var index = 0;
function refreshScript (src) {
var scriptElement = document.createElement('script');
scriptElement.type = 'text/javascript';
scriptElement.src = src + '?' + index++;
document.getElementsByTagName('head')[0].appendChild(scriptElement);
}
然后在Firebug控制台中,您可以将其称为:
Then in the Firebug console, you can call it as:
refreshScript('my_script.js');
您需要确保索引本身不是正在重新加载的脚本的一部分!
You'll need to make sure that the index itself is not part of the script being reloaded!
Firebug Net面板将帮助您查看是否正在下载脚本。响应状态应该是200 OK而不是304 Not Modified。此外,您应该看到查询字符串中附加了索引。
The Firebug Net panel will help you see whether the script is being downloaded. The response status should be "200 OK" and not "304 Not Modified. Also, you should see the index appended in the query string.
Firebug HTML面板将有助于你看看脚本元素是否附加到head元素。
The Firebug HTML panel will help you see whether the script element was appended to the head element.
更新:
这是一个版本使用时间戳而不是索引变量。正如@davyM建议的那样,这是一种更灵活的方法:
Here is a version that uses a timestamp instead of an index variable. As @davyM suggests, it is a more flexible approach:
function refreshScript (src) {
var scriptElement = document.createElement('script');
scriptElement.type = 'text/javascript';
scriptElement.src = src + '?' + (new Date).getTime();
document.getElementsByTagName('head')[0].appendChild(scriptElement);
}
阿列克谢的观点也很明确。
Alexei's points are also well-stated.
这篇关于有没有办法在开发时刷新javascript包含?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!