lvil
lvil

Reputation: 4336

Dynamically added Javascript won't reload

I have a web page with a Javascript file added dynamically. After changing the script (adding allert or smth like this) I reload the page, and push a trigger button for adding the script, but the browser uses the old one (chached). Tried it in chrome and IE. Other scripts (that are not added dynamically) reload well.

Here is the function that loads the script:

function addScript (s)
{
    script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = s;
    document.getElementsByTagName('head')[0].appendChild(script);
    script.onload=function () 
    {
        switch (s)
        {
            case 'some address':
                 functionInTheNewFile(); break; 
            default: break; 
        }
    };
}

What is wrong here?

Upvotes: 2

Views: 624

Answers (2)

Tom Gullen
Tom Gullen

Reputation: 61755

If it is an external script caching, append the current date and time to the end of the script. IE:

var nowDate = new Date();
script.src = s + "?nocache=" + nowDate.getTime();

Upvotes: 2

Struppi
Struppi

Reputation: 163

IE do not fire the load event, you have to use attachEvent instead. And always add the eventlistener before you locate the script.

script = document.createElement('script');
script.type = 'text/javascript';
if(script.attachEvent) {
script.attachEvent('onreadystatechange', callback);
} else {
    script.onload = callback;
}
script.src = s;

Upvotes: 0

Related Questions