views:

53

answers:

4

I prepare a project with a simple webpage, canvas, and javascript files that run game in the canvas. I want load my code when page starts, what is best way?

  1. put body onload?
  2. startup code in body of .js file (not in function)?
  3. attach to window load event?
  4. use some jquery capability?

Thanks!

+4  A: 

You can attach to when the page loads using jQuery like this:

$(function() {
    // Your code here.
});

If that's the only thing you'd be using jQuery for, though, I'd probably stick with your third option you listed there.

icktoofay
this works just like placing in $(document).ready?
zaharpopov
`$(some function)` is exactly the same as `$(document).ready(some function)`
icktoofay
A: 

Use $(document).ready

$(document).ready(function() { code goes here; } );
Kyle Butt
why is different from the answer here: http://stackoverflow.com/questions/2256621/way-to-load-javascript-code-in-web-page/2256624#2256624 ?
zaharpopov
because $(function) is a shortcut for $(document).ready(function)
Kyle Butt
+1  A: 

Javascript and jQuery code is generally best put right before the </body> tag.

Robert Harvey
sorry, can you elaborate? I guess my js goes into <script> tag linking to .js file - what next?
zaharpopov
Exactly right. Documentation for `<script>` tag is here: http://www.w3schools.com/TAGS/tag_script.asp
Robert Harvey
@zaharpopov> Just place your <script> tags after the bulk of the document body, just prior to the close of the body tag as mentioned. The page will load and render, and whatever JS is to be loaded and executed will be done immediately after. There is no need to call onload or $(document).ready(). This method is advantageous because all of the images and markup load, and the user isn't waiting for the JS to load before they can view the page.
bdl
@bdl: so if I have script initialization code and use this method, I just place it in the body of the .js file (outside functions)?
zaharpopov
A: 

Since you are using jQuery, you should use the facilities it provides..

$(document).ready(
function(){

   /*You code goes here..*/


});
Gaby