While developing an administrative interface for a web application I only wanted to load the CSS stylesheet for the administrative view when it was needed. KRL provides the ability to define CSS in the global section and load external CSS files. However, both methods insert the CSS into the page every time the Ruleset is evaluated. I really did not want to load hundreds of lines of useless CSS into every page.



My solution was to harvest the load external stylesheet code from the KRL runtime and wrap it in a defaction.

loadStylesheet = defaction(cssURL) {
  loadCode = <<
    var head=document.getElementsByTagName('head')[0];
    var new_style_sheet=document.createElement("link");
    new_style_sheet.href="#{cssURL}";
    new_style_sheet.rel="stylesheet";
    new_style_sheet.type="text/css";
    head.appendChild(new_style_sheet);
  >>;
  emit << eval(loadCode);  >>;
};

Now I can load external stylesheets programatically:

rule inject_css {
  select when click "#ignite"
  {
    loadStylesheet("http://assets.lobosllc.com/css/inception.css");
  }
}