views:

29

answers:

3

In java script I am including a source file like usual

<script src="http://source.com?file=1" type="text/javascript"></script>

The problem is that sometimes the file is not accessible and it throws an exception. Is there any way to include a file like this but if its not available catch the exception and navigate to a new page? I don't want all exceptions to navigate to a new page, just this one instance.

A: 

If the file is accessible and loads, the script element will fire an onload event. You could set a timeout that would redirect after a certain period of time, and have the onload handler cancel that timeout.

JacobM
A: 

Dynamic script tag insertion might be an option to you.

var insertScript = function(name){
    var scr = document.createElement('script');

    scr.src  = name;
    scr.type = 'text/javascript';       

    scr.onload = scr.onreadystatechange = function(){
        if(scr.readyState){
            if(scr.readyState === 'complete' || scr.readyState === 'loaded'){
                scr.onreadystatechange = null;
                // script was loaded successfully                                                                       
            }
        } 
        else{                               
            // script was loaded successfully
        }
    };  

    scr.onerror = function(){
        window.location.href = "http://www.foobar.com";
    };

    head.insertBefore(scr, head.firstChild);
}; 

Usage:

insertScript("http://source.com?file=1");
jAndy
A: 

Yes, insert the script using javascript:

<script type="text/javascript">
try {
    var newscript = document.createElement('script') ;
    newscript.type='text/javascript' ;
    newscript.src='http://source.com?file=1' ;
    document.getElementsByTagName("head")[0].appendChild(newscript) ;
} catch(e) {
    // Timeout/error handling here.
}
</script>
Gus