None

Javascript and the DOM

November 20, 2009

An Inconvenient API - The Theory of the DOM(2006)

Douglas Crockford

Linking to script files

  • You don't need language="javascript" in scripts
  • Also don't need to comment code with HTML comments
  • type="text/javascript" ignored if doing src=

Tips

  • Put script src= at bottom of html (for performance)
  • put css at top of html (so it's loaded before javascript)
  • minify javascript
  • don't use document.write

Don't use provided collections in dom, use

  • document.getElementById(id)
  • document.getElementsByName(name)
  • node.getElementsByTagName(tagName)

Part 2

  • node.style.stylename to change specific stylename
  • Getting actual style is different in IE and everything else

Creating nodes:

  • document.createElement(tagName)
  • document.createTextNode(String)
  • node.cloneNode()
  • note.cloneNode(true) - true means deep

Your new nodes are not connected yet!

  • node.appendChild(new_node)
  • node.insertBefore(new_node, sibling)
  • node.replaceChild(new_node, old_node)
  • old_node.parentNode.replaceChild(new_node, old_node)

Remove event handlers before deleting! (IE6 bug)

  • node.removeChild(old)
  • old.parentNode.removeChild(old)

Creating events - node["on" + event_type] = f; works on all browsers

Part 3

  • Don't use alert in AJAX apps - it blocks, and causing timing problems

a script can access another window if:

  • it can get a reference to it
  • document.domain === otherwindow.document.domain
  • can change document.domain on the fly to match?

The DOM is a mess (2009)

John Resig

  • All DOM functions have a bug in some browser somewhere
  • getElementById - doesn't work on XML

  • getElementsByClassName - new, works in Firefox 3 Safari 3 Opera 9.6

  • Opera - only matches first class if more than one class on an element

querySelectorAll - new in Firefox 3.1 Safari 3.1 Opera 10 IE 8

  • use CSS Selector to find DOM elements

  • Add stylesheets before jquery itself

  • http://mankz.com/code/GlobalCheck.htm - compare javascript libraries

  • Feature detection - run code to see if a feature works before using it

  • Modern jQuery selector is bottom up - works right to left

If you want to run a script

  • fetch it from the server as text
  • dynamically create a script tag
  • put script in (which runs it) then remove it
  • works in all browsers

Tags: javascript dom jquery