我正在开发一个 HTML5 facebook 游戏(在 facebook canvas iframe 内),除了一些其他 js 文件、css 文件(图像文件,在 css 文件中)、字体文件、声音文件和屏幕( html div 在单独的文件中)。
我想要一个加载脚本,因为资源大小约为 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 之后/Body 标签结束之前())
<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
,它将显示框架并清除间隔。否则它只会继续检查。
关于javascript - html5游戏客户端渲染html资源加载策略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20237519/