Async scripts for asm.js - Game development 编辑

Every medium or large game should compile asm.js code as part of an async script to give the browser the maximum flexibility to optimize the compilation process. In Gecko, async compilation allows the JavaScript engine to compile the asm.js off the main thread when the game is loading and cache the generated machine code so that the game doesn't need to be compiled on subsequent loads (starting in Firefox 28). To see the difference, toggle javascript.options.parallel_parsing in about:config.

Putting async into action

Getting async compilation is easy: when writing your JavaScript, just use the async attribute like so:

<script async src="file.js"></script>

or, to do the same thing via script:

var script = document.createElement('script');
script.src = "file.js";
document.body.appendChild(script);

(Scripts created from script default to async.) The default HTML shell Emscripten generates produces the latter.

When is async not async?

Two common situations in which a script is *not* async (as defined by the HTML spec) are:

<script async>code</script>

and

var script = document.createElement('script');
script.textContent = "code";
document.body.appendChild(script);

Both are counted as 'inline' scripts and get compiled and then run immediately.

What if your code is in a JS string? Instead of using eval or innerHTML, both of which trigger synchronous compilation, you should use a Blob with an object URL:

var blob = new Blob([codeString]);
var script = document.createElement('script');
var url = URL.createObjectURL(blob);
script.onload = script.onerror = function() { URL.revokeObjectURL(url); };
script.src = url;
document.body.appendChild(script);

The setting of src rather than innerHTML is what makes this script async.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:116 次

字数:2644

最后编辑:7年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文