JavaScript Tip: Waiting for the DOM to Load

As we have started to learn about the DOM this season, one thing that is an issue when developing your scripts is knowing when you can have your scripts execute. Remember, the DOM is available to you only when it has finished loading in the browser. You may ask, when has it finished loading? Good Question!

The order of completion that takes place inside a browser is roughly:

1. HTML is parsed
2. External scripts/style sheets are loaded
3. Scripts are executed as they are parsed in the document
4. DOM is fully constructed
5. Images and external content are loaded
6. The page is finished loading
Continue reading

JavaScript Tip: Using Timers

Timers are a way to add a dynamic aspect to your web pages. They can be used to create animations, open or close windows, pop up a message to the user, and even destroy a cookie for security purposes.

There are two types of timers: one that’s set once, and one that reoccurs over an interval. Both can be canceled, though the one-time timer method fires just once.

To create a nonrepeating timer, use the setTimeout method. It takes a minimum of two parameters: the function literal or function name to run the timer delay ends, and the length of the timer delay in milliseconds. Continue reading

JavaScript Tip: Ternary Operator

Using many if or switch statements can make your code very long and complex in no time. A trick to avoid some of the bloating involves using something called the ternary operator.

The ternary operator syntax is:

This is very handy for boolean conditions or very short values. Continue reading

JavaScript Tip: Image Preloading

Pre-loading (caching) images is as easy as creating a new image object and setting the object’s src property.

But what if we have several images to load?

What makes this preloading is that you do it before you need to replace an image currently on the web page. One way to preload is to create an array at the beginning of a script containing the paths to all graphics you wish to preload, then loop through that list, creating a new image object for each one:

Continue reading