HTML5游戏的客户端呈现HTML资源的加载策略
问题描述:
我正在使用jQuery中除了一些其他js文件,css文件(图像文件,在css中)的HTML5 facebook游戏文件),字体文件,声音文件和屏幕(html div在单独的文件中)。HTML5游戏的客户端呈现HTML资源的加载策略
我想要一个加载脚本,因为资源的大小大约为1 MB。有两种选择;
第一个是写一个资源加载器,并以正确的顺序加载所有东西,这真的很痛苦。
第二个是在启动时首先有一个简单的加载屏幕,在加载这个页面时开始加载实际的html(带有js,css和everyting)并将加载过程交给浏览器客户。
<!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:Example 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
,它将显示帧并清除间隔。否则它将继续检查。
你的答案部分正确。我也需要动态加载的资源来通知父母。举一个例子,我需要确定浏览器类型并相应地加载mp3/ogg,这可以通过javascript完成。因此,我需要处理iframe中的加载处理程序并加载动态资源,如音频文件,然后才发送加载的信号。 – hevi
当你说'在iframe中'你只是指iframe链接到的页面?如果是这样,你可以尝试在父页面上运行一个'setInterval'来检查子变量是否被设置为true,也就是说,只有在完成加载和完成时,Child设置为'var done = true;' == true'显示框架。 – Nunners
@hevi请参阅我的编辑答案与新的例子。 – Nunners