简体   繁体   中英

Reload JavaScript files without refreshing HTML

I've a HTML which loads several Javascript files:

<script src="assets/js/a.js"></script>
<script src="assets/js/b.js"></script>
<script src="assets/js/jquery.min.js"></script>

As I debug/test my Javascripts in my browser's console, is it possible to reload these Javascript files without the need to reload the entire HTML page?

You could remove and then re-add them:

$('script').each(function() {
    if ($(this).attr('src') !== 'assets/js/jquery.min.js') {
        var old_src = $(this).attr('src');
        $(this).attr('src', '');
        setTimeout(function(){ $(this).attr('src', old_src + '?'+new Date()); }, 250);
    }
});

Nope (at least not without a hack), in fact - be very careful reloading so much. It's quite possible that your javascripts become cached, which leads to many-a-headache trying to debug, since your updates are not applying.

https://superuser.com/questions/36106/force-refreshing-only-javascript-files-in-firefox-and-chrome

Tested with jQuery 2.0.3 and chrome 43

 function reloadScript(id) {

    var $el =  $('#' + id);

    $('#' + id).replaceWith('<script id="' + id + '" src="' + $el.prop('src') + '"><\/script>');
}

Chrome is complaining, but works:

Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check http://xhr.spec.whatwg.org/ .

Your script tag has to have id. Call in console:

reloadScript('yourid');

Does not remove event listeners, so for for example button click gets executed twice if once reloaded.

Based on PitaJ's solution.

Reload all javascript in a function. You can call this from anywhere you want.

 $('script').each(function () {
        if ($(this).attr('src') != undefined && $(this).attr('src').lastIndexOf('jquery') == -1) {
            var old_src = $(this).attr('src');
            var that = $(this);
            $(this).attr('src', '');

            setTimeout(function () {
                that.attr('src', old_src + '?' + new Date().getTime());
            }, 250);
        }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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