Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there anything more reliable than $(document).ready()?

I have a utility that draws a simple arc, either using SVG or, as a fallback, Canvas. (An early version can be found in my Raphael Arcs Project on my website.

To accomodate a mobile solution, I recently added code to monitor the size of the container and, if it changes, to re-draw the image to fit the newly sized container. This addition uses only the size of the containing DIV; the code adds either a SVG or Canvas object to the DIV.

Repeatedly reloading the page, however, sometimes the DIV layout isn't ready even when $(document).ready says it is. This seems to be most prevalent under Chrome; I've seen it only once with Opera and never with Firefox 3.6. The height and width of the containing DIV come back as zero.

If you load the link above in Chrome and hit reload, every tenth hit or so the Canvas demo will show a similar flaw: it will be sized width: 100% of viewport, height: 300px, and the demo will not draw correctly.

I've looked through the jQuery documentation and it seems to insist that $(document).ready() ought to be enough. I'd rather not have 12% of my users experience a browser-related failure. Other than writing my own layout probe (a spinning Timeout asking, over and over, "is the container sized yet?"), is there a common technique or library to assure that not only is the DOM loaded but the layout manager has settled?

[EDIT]

I've ended up doing something like this (code is Coffeescript):

$(document).ready ->
    $('.wrapper').each ->
        demo = =>
            c = new CanvasArc $('.canvas_demo', this)
            c.sweep(1.0)
            r = new RaphaelArc $('.raphael_demo', this)
            r.sweep(1.0)
        scan = =>
            if $('.canvas_demo', this).height()
                demo()
            else
                setTimeout(scan, 100)
        scan()

I really shouldn't have to do that.

like image 738
Elf Sternberg Avatar asked Jun 24 '11 15:06

Elf Sternberg


1 Answers

You are right that you shouldn't have to work around this. The answer is hidden in the .ready() section:

When using scripts that rely on the value of CSS style properties, it's important to reference external stylesheets or embed style elements before referencing the scripts.

So all you need to do is include your CSS first and then your scripts. This way, your ready-event handler isn't even being set until after the CSS has been loaded.

like image 191
Borgar Avatar answered Sep 23 '22 17:09

Borgar