I'm trying to load a javascript file locally with getScript, but it returns a 404 error.
test.js - the script I'm trying to load:
var hello = function(){
alert( "test" );
}
hello();
jQuery code from index.html:
<script type='text/javascript'>
$.getScript( "js/test.js" )
.fail( function( e ){ $( 'body' ).html( JSON.stringify( e ) ) } )
.done( function(){ alert( "Success" ) } );
</script>
When I open index.html in Chrome, getScript fails, and the following is displayed in the body:
{"readyState":4,"responseText":"","status":404,"statusText":"error"}
So obviously jQuery can't find the file specified. But the weird thing is, when I use the traditional tags:
<script type='text/javascript' src='js/test.js'></script>
it works fine.
Also, getScript works fine if I'm loading from an external site, such as:
$.getScript( "http://www.youtube.com/player_api" )
So what could be the problem?
Ahhh, the key is that you're running this on your local machine and trying to fetch a script from your local hard drive.
The issue is that
$.getScript()
uses an Ajax call to load the script and Ajax calls are not allowed by default to fetch contents from your hard drive in some browsers (like Chrome) for security reasons. This would not be an issue if loading from a real web server.You can work around it by inserting a script tag yourself instead of using jQuery's
$.getScript()
or by not trying to run this from your local hard drive. There is also a Chrome command line parameter that will bypass this security restriction which you could use for development purposes (not recommended for general purpose browsing).