0

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!

2
  • Can you tell us which library, if any, you use? Commented Feb 13, 2010 at 6:13
  • @Sudhir: yes sure. I use jQuery Commented Feb 13, 2010 at 6:47

4 Answers 4

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

$(some function) is exactly the same as $(document).ready(some function)
1

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

4 Comments

sorry, can you elaborate? I guess my js goes into <script> tag linking to .js file - what next?
Exactly right. Documentation for <script> tag is here: w3schools.com/TAGS/tag_script.asp
@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: so if I have script initialization code and use this method, I just place it in the body of the .js file (outside functions)?
0

Use $(document).ready

$(document).ready(function() { code goes here; } );

2 Comments

why is different from the answer here: stackoverflow.com/questions/2256621/… ?
because $(function) is a shortcut for $(document).ready(function)
0

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

$(document).ready(
function(){

   /*You code goes here..*/


});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.