Reputation: 197
I am new to javascript and I have a question regarding loading and confirming loading of all assets, scripts, etc before allowing a game to continue. Basically, how to know when all assets and scripts are loaded...
This seems like a trivial problem/question, but I have asked several programmers and no one seems to have a definitive answer.
I have a html page to load with assets- ie pngs, etc all designated vis css - nothing designated in-line.
I also have many custom javascript classes, etc, including jquery, loading.
I am currently using this to confirm page load- when page load function is run, content becomes visible. There is a small loading spinner on the page that gets removed.
I am using the jQuery standard loading script -- $(document).ready(function()
</head>
<body onload="doAfterPageLoad()">
<div id="wrapper" >
<div id="loadingIcon" >
<div id="loadingWord"></div>
</div>
<div id="content" style="visibility: hidden;">
<!-- html stuff here -->
</div>
</div>
</body>
</html>
//Javascript jQuery stuff....
<script type="text/javascript">
function doAfterPageLoad()
{
$("#loadingIcon").css("visibility","hidden");
$("#content").css("visibility","visible");
}
$(document).ready(function()
{
// start javascript stuff
});
</script>
My question - is this synchronizing? (I am on fast connection and cannot tell) Is it possible that something could get out of order?- should I set a variable and count when both “loads” are complete and use that to start game? And, if I choose to load some png asset files via a javascript loader, should that provide a third variable/value needed to trigger that the load is complete?
Upvotes: 3
Views: 3985
Reputation: 3542
The best solution for this I've found has been using requirejs.
In short, it solves just this problem, allowing you to load scripts as you need them, and know that they are loaded. It makes the application faster because you only load scripts when you need them.
The basic syntax is:
require(
["jquery","module"], // these are your dependancies
function($,module){ // this is what you want to do after your deps have been loaded
// do stuff
});
In requirejs, each dependancy module is defined in its own file. Your modules are wrapped in a define() function to allow requirejs to pull it:
define(
["jquery"], // these are your dependancies
function($){ // this is what you want to do after your deps have been loaded
var module= {
// my widget definition
};
return module;
});
Upvotes: 0
Reputation: 47677
jQuery provides the load()
function, so instead of $(document).ready
do
$(window).load(function()
{
// start javascript stuff
});
and it will fire when all the assets are loaded
Upvotes: 3
Reputation: 18595
You had the right idea. Throw all of your DOM ready dependent items inside of:
$(document).ready(function()
{
// start javascript stuff
});
Like you said, this is allowing the html to render on the page first before allowing the javascript execute.
Upvotes: 0