Henrik Franzén Henrik Franzén - 1 year ago 56
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:


<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>


function waitForJS() {
var shouldStop;

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

if (shouldStop === true) {
//PIXI has loaded

} 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 Source

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


<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() {

Note that you should avoid globals