Cover by Cody Lindley

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

8.6. Accessing an Element ASAP (Before document.ready)

Problem

You need to gain access to a certain DOM element as soon as possible.

Using document.ready isn’t fast enough; you really want to control this element before the page finishes rendering.

Issues like this are especially noticeable on large pages, where the document.ready event takes longer to be reached.

Solution

This is a very common and generic problem that can be solved in many different ways.

There’s one approach that works for all of them, but it requires polling the DOM so it adds overhead to the page-rendering process (definitely undesirable!).

These are some of the usual problems where one could rely on polling:

  • Hide an element right away, before it is rendered (or another style operation)

  • Bind event handlers to an element ASAP so that it quickly becomes functional

  • Any other situation

We’ll discuss what’s the better approach for each situation in the “Discussion” section.

Discussion

Hide an element right away (or another style operation)

So, your problem is directly related to styling, you want to apply a conditional styling to an element, and this condition needs to be evaluated by JavaScript.

The right way to go about this is adding a specific CSS class to an element that is quickly accessible, like the <html> element, and then style the element accordingly.

Do something like this:

<!DOCTYPE html> <html> <head> <style type="text/css"> html.no-message #message{ display:none; } </style> <script src="assets/jquery-latest.js"></script> ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required