|
1 | 1 | /**
|
2 | 2 | * # GameWindow
|
3 |
| - * Copyright(c) 2019 Stefano Balietti <ste@nodegame.org> |
| 3 | + * Copyright(c) 2020 Stefano Balietti <ste@nodegame.org> |
4 | 4 | * MIT Licensed
|
5 | 5 | *
|
6 | 6 | * API to interface nodeGame with the browser window
|
|
2186 | 2186 |
|
2187 | 2187 | func();
|
2188 | 2188 |
|
2189 |
| - // Important. We need a timeout (2nd param), because some changes |
2190 |
| - // might take time to be reflected in the DOM. |
2191 |
| - W.adjustFrameHeight(0, 120); |
| 2189 | + adjustFrameHeightAfterLoad(); |
| 2190 | + |
2192 | 2191 | };
|
2193 | 2192 |
|
2194 | 2193 | if (loadCache) reloadScripts(iframe, afterScripts);
|
|
2413 | 2412 | }
|
2414 | 2413 | }
|
2415 | 2414 |
|
| 2415 | + /** |
| 2416 | + * ### adjustFrameHeightAfterLoad |
| 2417 | + * |
| 2418 | + * Adjusts the frame height after frame is loaded |
| 2419 | + * |
| 2420 | + * It waits 120ms or until all images are loaded. |
| 2421 | + * |
| 2422 | + * @see handleFrameLoad |
| 2423 | + */ |
| 2424 | + function adjustFrameHeightAfterLoad() { |
| 2425 | + |
| 2426 | + // Kudos: |
| 2427 | + // https://stackoverflow.com/questions/11071314/ |
| 2428 | + // javascript-execute-after-all-images-have-loaded |
| 2429 | + |
| 2430 | + var doc, imgs, len, counter, increment; |
| 2431 | + doc = W.getFrameDocument(); |
| 2432 | + imgs = doc.images; |
| 2433 | + len = imgs.length; |
| 2434 | + |
| 2435 | + // If there are no images, we wait a fixed 120 milliseconds. |
| 2436 | + if (!len) { |
| 2437 | + // Important. We need a timeout (2nd param), because some changes |
| 2438 | + // might take time to be reflected in the DOM. |
| 2439 | + W.adjustFrameHeight(0, 120); |
| 2440 | + return; |
| 2441 | + } |
| 2442 | + |
| 2443 | + // Else we wait until all images are loaded. |
| 2444 | + counter = 0; |
| 2445 | + increment = function() { |
| 2446 | + if (++counter === len) W.adjustFrameHeight(); |
| 2447 | + }; |
| 2448 | + |
| 2449 | + [].forEach.call(imgs, function(img) { |
| 2450 | + if (img.complete) increment(); |
| 2451 | + else img.addEventListener('load', increment, false); |
| 2452 | + }); |
| 2453 | + } |
| 2454 | + |
2416 | 2455 | //Expose GameWindow prototype to the global object.
|
2417 | 2456 | node.GameWindow = GameWindow;
|
2418 | 2457 |
|
|
0 commit comments