Window.onload Not Running On Page Refresh
Solution 1:
It does not look like your code is complete in your question but I'm going to hypothesize the following. What you describe looks like a race condition:
When the cache does not contain your data, the assignment to
window.onload
happens before theonload
even is fired, so your handler is called.When the cache already contains your data, then the
onload
event is fired before the assignment towindow.onload
happens, so your handler is never called.
I would suggest using the domReady
plugin because it is designed to handle both cases. I've never used it myself but from what I can gather from the documentation, something like:
require(['domReady!', 'game','comm','misc','soundutil','sprite','gui','constants'],...
should work. The exclamation mark is not a typo, by the way. You then need to make your onload
handler be the body of the function you pass to require
.
Note that document.onload
suffers from the same problem. It is even more prone to the problem you're having because it often fires before window.onload
does.
ETA: As Shrike says, you can also use the jQuery method of waiting: $(document).ready(...)
. My rule of thumb here is if I'm already using jQuery (which I actually do in all my current projects), then I'd use $(document).ready(...)
, otherwise I'd use domReady
. The difference between the two methods has been examined in detail in this question.
Solution 2:
It's because at the moment of your code execution window is already loaded. So you're subscribing on an event which never fires. I'm not sure what kind if cache did you mean and why window's load fires.
You can easy fix your code if you use jQuery:
require(['game', 'comm', 'misc', 'soundutil', 'sprite', 'gui', 'constants'], function(Game, COMM, MISC,SoundUtil, Sprite, Gui,CNT){
$(document).ready(function () {
});
});
Solution 3:
By the time RequireJS is done preparing dependencies and executes the factory function the onload
could have already happened, in this case your custom handler will not be executed as it is already late (the "onload train" already left).
A RequireJS-specific alternative is to use the domready plugin:
require(['a', 'b', 'domready'], function (A, B, domReady) {
domReady(function () {
var canvas = document.getElementById('gameCanvas'),
game = document.getElementById('game'),
g = null,
su = null;
canvas.width = document.body.clientWidth;
canvas.height = document.body.clientHeight;
console.log('Gamestate at beginning', CNT.GameState._current);
// ...
});
});
More details about domready plugin in the official documentation
Post a Comment for "Window.onload Not Running On Page Refresh"