html5游戏客户端渲染html资源的加载策略

Loading strategy of client side rendered html resources for html5 game

本文关键字:资源 加载 策略 html 游戏 客户端 html5      更新时间:2023-11-12

我正在开发一款HTML5 facebook游戏(在facebook画布iframe中),在该游戏中,我除了使用一些其他js文件、css文件(在css文件中的图像文件)、字体文件、声音文件和屏幕(在单独的文件中的htmldiv)外,还使用了jquery。

我想要一个加载脚本,因为资源的大小大约是1MB。有两种选择;

第一个是编写一个资源加载程序,并按正确的顺序加载所有内容,这真的很痛苦。

第二个是首先在启动时有一个简单的加载屏幕,在加载这个页面时,它将被快速加载,开始加载实际的html(带有js、css和everthing),并将加载过程移交给浏览器客户端。

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
    function iframeIsLoaded()
    {
        ...
    }
</script>
</head>
<body>
    <div id="loadingScreen" class="..."> <!-- iframe will be under this div -->
    ...
    </div>
    <iframe ...>
    </iframe>
...

显然,第二个选项要好得多,但我不知道该怎么做。如上所示,我可能在加载屏幕div下使用iframe,但有没有办法从iframe向上层div发送消息?

我也对其他解决方案持开放态度!

您可以使用iframe.load事件来执行此操作。

您要做的是在页面加载时隐藏iframe并显示加载屏幕,然后等待内容加载,然后显示框架并隐藏加载屏幕。

(本例假设您使用IFrame的src属性来加载内容)

纯Javascript:示例JSFiddle

var frame = document.getElementById('iframeID');
var loading = document.getElementById('loadingScreen');
frame.style.display = 'none';//Originally hide the frame
loading.style.display = 'block';//Originally show the Loading Screen
frame.src = 'http://www.bing.com';//Set the src attribute
frame.onload = function() {
    frame.style.display = 'block';//Show the frame after it is loaded
    loading.style.display = 'none';//Hide the loading screen
}

编辑:(删除jQuery示例并添加基于注释的新示例)

这里有一个新的例子,它检查变量done的子页面,以检查它是否设置为true。

警告由于跨域脚本安全性,此示例可能不起作用,只有当您100%确信两个页面都在同一域上时,才应使用此示例

子页面:

    var done = false;
    setTimeout(function () {
        done = true;
    }, 10000);

父页:(脚本需要放置在HTML之后/正文标记()结束之前)

<div>
    <div id="loading">
        Loading...
    </div>
    <iframe id="iframeID"></iframe>
</div>
<script type="text/javascript">
    var frame = document.getElementById('iframeID');
    var loading = document.getElementById('loading');
    frame.style.display = 'none'; //Originally hide the frame
    loading.style.display = 'block'; //Originally show the Loading Screen
    frame.src = 'Test2.aspx'; //Set the src attribute
    frame.onload = function () {
        console.log('Loaded Frame');
    }
    var $interval = setInterval(CheckFrameDone, 500);
    function CheckFrameDone() {
        var done = frame.contentWindow.done;
        console.log(done);
        if (done) {
            console.log('Frame is Finished Loading');
            frame.style.display = 'block';
            loading.style.display = 'none';
            clearInterval($interval);
        } else {
            console.log('Still Waiting...');
        }
    }
</script>

在第二个示例中,您会注意到,每500毫秒,父页面就会检查子页面的done值,如果是true,则会显示帧并清除间隔。否则,它将继续检查。