Typescript window.onload not being called after adding requirejs for phaser game

koreus737 picture koreus737 · Aug 9, 2015 · Viewed 24.6k times · Source

I am trying to make a game with phaser and Typescript. I followed the instructions here and it worked initialy. The problems came when I tried to modularise my code using AMD and requirejs

index.html

<!DOCTYPE html>

<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>Resonate</title>
    <link rel="stylesheet" href="app.css" type="text/css" />
    <script src="phaser.js"></script>
    <script src="http://requirejs.org/docs/release/2.1.20/minified/require.js" data-main="app"></script>
</head>
<body>
    <h1>RESONATE</h1>

    <div id="content"></div>
</body>
</html>

Player.ts

export class Player {

    color: string;

    constructor() {
        this.color = "#0000ff";
    }
}

app.ts

import player = require("Player");

class PhaserDemo {

    game: Phaser.Game;

    constructor() {
        this.game = new Phaser.Game(800, 600, Phaser.WEBGL, 'content', { preload: this.preload, create: this.create });
    }

    preload() {
        this.game.load.image('phaser_run', 'run.png');
    }

    create() {
        console.log("Before");
        var p = new player.Player();
        this.game.stage.backgroundColor = p.color;
    }
}

window.onload = () => {
    console.log("ONLOAD");
    var game = new PhaserDemo();
};

Now when I load it up window.onload is never called, I tried following window.onload not calling function for the Javascript solution but I can't get it to work in typescript.

Also here is the generated Javascript if you want to take a look https://gist.github.com/koreus7/06bee4a30d22bdc76d62

Answer

basarat picture basarat · Aug 10, 2015

for the Javascript solution but I can't get it to work in typescript.

Basically if the window is already loaded attaching to window.onload will not call the attached function.

Check for document.readyState === "complete". Alternatively use something like jquery ready : https://api.jquery.com/ready/