Javascript game, module raphael not defined

微笑、不失礼 提交于 2019-12-12 05:48:16

问题


I am developing a game engine here: http://synodins.com/apps/tank_fight But now, for some reason, it doesn't run anymore. I cannot initiate the Raphael module, when i run the site with mozilla web debugger, i get "Raphael is not defined". But that doesn't make any sense because it's very clearly defined in the raphael.js module.

Also, occationally the game runs fine, like, every 20th time i try. And there's no clear pattern to what makes it work.
I print out Hello world 1 before trying to initiate raphael, and hello world 2 after trying.
Can anybody see what the problem is?


回答1:


The block of load_script calls loads the scripts asynchronously. This is why there appears to be no clear pattern.

There is no guarantee that raphael.js is loaded (and therefore, that Raphael is defined) by the time that the line:

var playing_area = Raphael(0,50,1600,1600);

is called.

You should wait until the whole document is ready before attempting to use variables defined in external scripts. Under normal circumstances, this is the onload event of the document. Various libraries like jquery also offer their own "ready" event, that you could tie to if you use them.

Is there any reason why you load the scripts in the way you do, rather than simply using markup, as below?

<script src="raphael.js"></script>



回答2:


You are loading your scripts on demand - and this will speed up your initial page load. But right after that you try execute code in raphael.js - but loading of js files take some time and you have to be sure that they're loaded before you start calling functionality in them.

You may have a look at Modernizer.load() - this helps you to synchronize loading of resources and add callbacks when loading completes: http://www.modernizr.com/docs/#load




回答3:


Have you tried moving 'raphael.js' to be included before anything else? It may be that Raphael is not defined at the point a script above it needs it.



来源:https://stackoverflow.com/questions/7848505/javascript-game-module-raphael-not-defined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!