2009
Apr
21

Dynamic Style Loading

Example
  1. var HTTPUTILITY = {
  2. getStyle: function(url, callback) {
  3. var isLoaded = false;
  4. var style = document.createElement("link");
  5. style.setAttribute("rel", "stylesheet");
  6. style.setAttribute("type", "text/css");
  7. style.setAttribute("href", url);
  8. style.onload = style.onreadystatechange = function() {
  9. if (!isLoaded && (!this.readyState || this.readyState === "loaded" || this.readyState === "complete")) {
  10. isLoaded = true;
  11. if (typeof callback === "function") {
  12. callback();
  13. }
  14. if (this.tagName.toLowerCase() === "link") {
  15. document.getElementsByTagName("head")[0].removeChild(this);
  16. }
  17. }
  18. }
  19. var head = document.getElementsByTagName("head")[0];
  20. head.appendChild(style);
  21. }
  22. };
Example
  1. function complete() {
  2. alert("complete");
  3. }
  4. HTTPUTILITY.getStyle("myStyle.css", function(){complete();});

View Demo

Related Post

    CSS Inclusion

回應 (Leave a comment)