繁体   English   中英

在窗口调整大小时重新加载JS文件

[英]Reload JS file on window resize

如何在调整窗口大小时重新加载单个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函数中。

您可以尝试像这样附加新的脚本标签:

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

});

})

像这样:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM