tommi
tommi

Reputation: 6973

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?

Upvotes: 24

Views: 59536

Answers (4)

Andras Sebo
Andras Sebo

Reputation: 1140

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);
        }
    });

Upvotes: 1

Dariux
Dariux

Reputation: 4233

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.

Upvotes: 0

PitaJ
PitaJ

Reputation: 15012

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);
    }
});

Upvotes: 19

Jordan Scales
Jordan Scales

Reputation: 2717

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

Upvotes: 2

Related Questions