Henrik Franzén Henrik Franzén - 6 months ago 15
Javascript Question

I'm loading scripts with setTimeout, can you find a faster way?

I have one file called main.min.js. This file has some parts which require the library pixi.min.js. The fastest way I can come up with to load these two parts is:

HTML

<script async src="//cdnjs.cloudflare.com/ajax/libs/pixi.js/3.0.11/pixi.min.js"></script>
<script async src="static/js/main.min.js"></script>


JAVASCRIPT

function waitForJS() {
var shouldStop;

if (typeof window.PIXI !== "undefined") {
shouldStop = true;
}

if (shouldStop === true) {
//PIXI has loaded
ThePixiFunction();
return;
}

setTimeout(waitForJS,30);
} waitForJS();





The reason I think this is the fastest way (for me) is because both files start loading at the same time, yet main.min.js starts executing before PIXI loads, and only the functions that need PIXI waits for it. Is there something about this I've overlooked? Or is there any better way of loading these two files?

Answer

Turns out it was stupid and I found a new way:

HTML

<script src="static/js/main.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/pixi.js/3.0.11/pixi.min.js" onload="PIXILoaded();"></script>

JS (in main.min.js)

window.PIXILoaded = function() {
        initPixiFunction();
};

Note that you should avoid globals