2

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?

1
  • Eval - Do an eval on the new JavaScript code for them to be "recognize" by the browser. Commented Feb 23, 2011 at 11:21

2 Answers 2

2

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();
Sign up to request clarification or add additional context in comments.

1 Comment

you're attaching the string representation of the Date() object - should be nowDate.getTime() or urlencoded
0

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;

1 Comment

maybe you know why IE has the error object is expected here: functionInTheNewFile(); break; Though it begins performing parts of the function

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.