0

How can I reload a single JS file on a window resize? I only need to reload a single JS file every time I resize the window so it wil reset the JS file. I have found here a script long time ago, but I can not find him.

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

Thnx gr Pascal

3 Answers 3

1

I don't see jQuery tagged, so the other responses likely won't work for you.

You basically need to capture the window resize event, which occurs for (practically) every pixel the browser is resized. This means you'll need to use setTimeout to wait for a finished resize (otherwise, you'll be reloading a script 1000x for every resize). Then you can set the source of the script to the same file, appending a timestamp that will force a non-cached refresh.

Here's how I would implement this: (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);

Note that the Javascript will need to either go after the original <script> definition, or placed into a window.onload function.

Sign up to request clarification or add additional context in comments.

Comments

0

you could try to append new script tag like that:

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

});

})

Comments

0

Like this:

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.