Load Script after game is loaded

For some reason, my code is running before the actual game, and I cannot access the $gameSystem global constructor. I tried this:


(function() {
$gameSystem.onBeforeSave();
})();


Did not work returned: Can not read property 'onBeforeSave' of undefined


Also tried


window.onload(function(){
$gameSystem.onBeforeSave();
})


Same Error,


What is going on? How do execute my code after $gameSystem is loaded.
I've moved this thread to Learning Javascript. Please be sure to post your threads in the correct forum next time. Thank you.
How about adding a check to see if $gameSystem exists?

Code:
if ($gameSystem) {
  // etc...
}
if ($gameSystem) {
// etc...
}



That wouldn't work because the if statement is being evaluated before $gameSystem is even loaded so of course it won't be defined. And when it is finally loaded that if statement won't run again.
Take a look at DataManager's load save function, perhaps you can write something to hook onto it.
Would it really be that complex? I'm sure i'm not the only scripter that needs this to be pulled off.
Oh, it's not complex to hook onto that. Just alias the method/function. What that does is essentially copy the original function (so that you can "call" it again, then you can write your own code below the function. Use "aliasname.call(this)" to call the original function, then add your own code above/below it.

Code:
var aliased_datamanager_function = Datamanager.someFunction;
Datamanager.someFunction = function () {
  aliased_datamanager_function.call(this);
  //etc code that you add
};
For some reason, my code is running before the actual game, and I cannot access the $gameSystem global constructor. I tried this:



(function() {
$gameSystem.onBeforeSave();
})();


Did not work returned: Can not read property 'onBeforeSave' of undefined


Also tried



window.onload(function(){
$gameSystem.onBeforeSave();
})


Same Error,


What is going on? How do execute my code after $gameSystem is loaded.



Can you explain what your code is doing?
JavaScript:
var alias_sceneBoot_start = Scene_Boot.prototype.start;
Scene_Boot.prototype.start = function() {
    alias_sceneBoot_start.call(this);
    // code goes here
}
Necro-post notice: @EvaarK

Original thread: https://forums.rpgmakerweb.com/threads/load-script-after-game-is-loaded.61648/