JS/CSS load order incoherency

    Date: 07/11/11 (Web Development)    Keywords: css, html, java

    [Edit: fixed CSS syntax in these examples. The development code is fine in that regard.]

    Using Firefox 5 on Windows 7, I ran into two related problems that must be common enough for there to be standard workarounds.

    1. CSS is not applied until after Javascript runs. Given the CSS:

    #id { width: 50px; }

    document.getElementById("id").style.width is undefined. This is using jquery's $(document).ready() which runs after everything else is supposed to be loaded. The standard body onload will run even earlier, with less of a chance that the CSS will be loaded if the problem is due to a race.

    Javascript can see the CSS style if it is set in the contents of an HTML style="" attribute, but you lose the benefits of CSS if you have multiple tags sharing the same style.

    2. Previously defined CSS does not apply to new nodes created by Javascript. [Edit #2: This does work. I had a typo in my code.]

    div.myclass { width: 50px; }  /* CSS */
    var node = document.createElement("div"); // JS
    node.setAttribute("class", myclass"); // CSS is not applied.
    node.className = "myclass"; // CSS is not applied.
    

    One solution to this one is to code every single CSS style change in Javascript using the DOM, but I would prefer not to have to do that.

    What are the best practices in these situations?

    Source: http://webdev.livejournal.com/575335.html

« Basic HTML Document || N00blet soup »


antivirus | apache | asp | blogging | browser | bugtracking | cms | crm | css | database | ebay | ecommerce | google | hosting | html | java | jsp | linux | microsoft | mysql | offshore | offshoring | oscommerce | php | postgresql | programming | rss | security | seo | shopping | software | spam | spyware | sql | technology | templates | tracker | virus | web | xml | yahoo | home