2014-10-09 73 views
0

如何重新加載窗口大小上的單個JS文件?每次調整窗口大小時,我只需要重新加載一個JS文件,以便重置JS文件。我很久以前在這裏發現了一個劇本,但我找不到他。在窗口調整大小重新加載JS文件

<script src="js/scripts.js" type="text/javascript"></script> 

日Thnx克帕斯卡爾

回答

1

我沒有看到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函數。

+0

它的工作原理!謝謝你飛 – Pascal 2014-10-09 12:38:25

0

,你可以嘗試添加新的腳本這樣的:

$(function(){ 
$('button').click(function(){ 
    var script = document.createElement('script'); 
    script.type = 'text/javascript'; 
    script.src = 'https://**.js'; 
    $("head").append(script); 

}); 

}) 
0

像這樣:

function bind() 
     { 
      $(window).resize(function() { $("#scriptToReload").attr("src", "reloadedScript.js"); }); 
     } 

$(document).ready(function() { bind();});