I’m making a simple javascript game engine for fun, and I’m running into a kind of annoying problem while working on it.
Currently the way I’m including javascript files is by having an index.html page that calls my javascript “main”, and includes all my javascript files with <script type="text/javascript" tags in the <head> section.
This is working reasonably well, except that maybe 1 in 6 or so refreshes of the page it fails to load one of the javascript files. I get an error like: GET http://localhost:8000/js/Input.js. It works fine when all the files are combined together and minified, so I assume this has something to do with asynchronous loading of the files and the game starting before everything is loaded? I’m not sure though. I’m including about 25 files right now, and the problem seems to be getting worse as I add more.
Is there a better way to include javascript files? I’m trying to make this as easy to work on as possible so I don’t want to have to do a ton of server-side stuff. (Currently I’m just using the SimpleHTTP server command in python)
If the error is an HTTP error, and the URL is exactly the same when it fails as when it succeeds, then the problem is not related with your JS but with your web server.
However, if you are using something like $.getScript and the error is related to some not initialized variable, you are probably looping through all your scripts to be included and executing a getScript for each one of them. If so, as getScript uses an AJAX request to load the JS, the execution order of the scripts is not guaranteed. To solve this, and if you don’t mind the performance hit as it seems this case is only when running on your development environment, you can chain the requests so no request is made before the previous (required) JS file is loaded, thus sequentially executing your script files: