Loading Javascript on your page properly

by kinabalu on July 11, 2009

Javascript Developing interactivity in your website pages will require you, to build a portion of it with javascript. If that javascript needs to perform its actions when the DOM has finished loading, you have several options depending on if you are using a javascript library or not. If you’re going the non-library route, you can do the following:
?View Code JAVASCRIPT
   window.onload = function() {
      // do something now that the dom is loaded
   }
The caveat here, is that based on what gets loaded first, you’ll have to ensure that you take into account any other code that needs to be post-DOM loaded. I would suggest using a library regardless, they make life oh so much more simple. First example is using mootools:
?View Code JAVASCRIPT
   window.addEvent('domready', function() {
        // do something now that the dom is loaded
   }
Here’s an example using jquery:
?View Code JAVASCRIPT
   $(document).ready(function() {
      // do something now that the dom is loaded
   }
And finally here’s an example using prototype:
?View Code JAVASCRIPT
   document.observe("dom:loaded", function() {
      // do something now that the dom is loaded
   }
So go forth, and remember the proper order of operations. No inlining your javascript folks!
Share this:
  • Digg
  • DZone
  • Facebook
  • Technorati
  • LinkedIn
  • del.icio.us
  • Google Bookmarks
  • E-mail this story to a friend!
  • TwitThis

{ 2 comments… read them below or add one }

minh tienNo Gravatar November 13, 2009 at 9:50 pm

window.onload = function() {
// do something now that the dom is loaded
}

window.addEvent(‘domready’, function() {
// do something now that the dom is loaded
}

$(document).ready(function() {
// do something now that the dom is loaded
}

document.observe(“dom:loaded”, function() {
// do something now that the dom is loaded
}

xanaxNo Gravatar March 2, 2010 at 7:50 am

Hello!
xanax ,

Leave a Comment

Previous post:

Next post: