如何在调整窗口大小时重新加载单个JS文件?每次调整窗口大小时,我只需要重新加载一个JS文件,这样它将重置JS文件。我很久以前就在这里找到了脚本,但找不到他。
<script src="js/scripts.js" type="text/javascript"></script>
Thnx gr帕斯卡
最佳答案
我没有看到jQuery被标记,因此其他响应可能对您不起作用。
基本上,您需要捕获窗口调整大小事件,该事件实际上发生在调整浏览器大小的每个像素上。这意味着您将需要使用setTimeout等待完成的调整大小(否则,您将为每次调整大小重新加载脚本1000x)。然后,您可以将脚本的源设置为同一文件,并附加一个时间戳,以强制进行非缓存刷新。
这是我要实现的方式:(http://jsfiddle.net/gbez11h2/)
HTML:
<script id="scriptToReload" type="text/javascript" src="path/to/script.js">
Javascript:
;(function (w, d) {
"use strict";
var timeout = null,
scriptEl = d.getElementById('scriptToReload'),
scriptSrc = scriptEl.src,
delay = 500; // How long to wait (in ms) before deciding resize is complete
w.onresize = function () {
// Clear previous timeout to indicate resizing is still occurring
w.clearTimeout(timeout);
timeout = w.setTimeout(function () {
// Resizing is (probably) done, now we can reload the script
// Start by destroying previous script element
scriptEl.parentElement.removeChild(scriptEl);
// Now we recreate the same element, with a timestamp cache-buster
scriptEl = d.createElement('script');
scriptEl.type = 'text/javascript';
scriptEl.src = scriptSrc + '?_=' + (new Date().getTime());
// And insert it into the DOM to be (re-)loaded
d.getElementsByTagName('head')[0].appendChild(scriptEl);
}, delay);
};
})(window, document);
请注意,Javascript必须要么遵循原始的
<script>
定义,要么放置在window.onload
函数中。关于javascript - 在窗口调整大小时重新加载JS文件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26275535/