2

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?

3
  • 2
    So look at the path, what is wrong with it. What should it be? Issue is not with getScript, the problem is with where the file is located. Commented Nov 10, 2014 at 19:14
  • Try using the full path starting with http:// and including the domain as a test so you can figure out why the path isn't working properly. Commented Nov 10, 2014 at 19:15
  • @jfriend00 I'm running this on my local machine if that matters. I've tried passing the url as both "/home/sorel/projects/test/js/test.js" and "file:///home/sorel/projects/test/js/test.js" and neither work. The latter opens in my browser. And again, using a <script> tag with src as the latter absolute path works as well, so I don't think it is a problem with the path I'm specifying. Commented Nov 10, 2014 at 19:49

1 Answer 1

4

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).

Sign up to request clarification or add additional context in comments.

1 Comment

Just FYI, you can also install "Web Server for Chrome" extension and use that to host your javascript files.

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.