Supplementary - On-Demand Loaders
Three Functions for Loading JavaScript and CSS Code Dynamically
T
ypically, web pages import CSS code statically by means of link elements within the head element. However, CSS can also be loaded dynamically, by inserting link elements explicitly into the page's DOM hierarchy. This page presents a small function that automates this technique, and which complements LoadLib_STH and LoadLib_XHR.
As with LoadLib_STH and LoadLib_XHR, this function can be used in conjunction with AspectJS, which is significant because the intersection of the two technologies permits style-sheet downloads on demand but entirely transparently at the point of need. This is explored in the AspectJS Applications page entitled On-Demand Loading.
Contents
LoadStyleSheet
LoadStyleSheet is presented in Listing One. It loads a style-sheet from the URL that is passed to it, and is an implementation of a variant on the 'Script-Tag Hack'.
When invoked it creates a <link> element dynamically, and sets that element's src attribute to the value of the URL supplied by the caller. It inserts the element into the DOM hierarchy for the page, which causes the browser to download and evaluate the style-sheet as if it had been included in the page statically.

 // Listing 1

 function LoadStyleSheet (StyleSheetURL)
    {
    var LinkElem = document.createElement ("link");

    LinkElem.setAttribute         ("rel",   "stylesheet");
    LinkElem.setAttribute         ("type",  "text/css");
    LinkElem.setAttribute         ("media", "all");

    document.getElementsByTagName ("head")[0].appendChild (LinkElem);

    LinkElem.setAttribute         ("href",   StyleSheetURL);

    }
            
Using LoadStyleSheet
Using LoadStyleSheet is a simple matter of calling the function, passing it the URL of the desired CSS file as a string; and Example One illustrates this. Here, clicking on the client area of the browser window causes the OnClick event handler to execute, which calls LoadStyleSheet before continuing.
Note that style-sheet loading is asynchronous, meaning that the call to LoadStyleSheet may return before the file has been retrieved from the server. This means that attempts to access and manipulate the attributes of a given element's Style object subsequent to a call to LoadStyleSheet may fail. Proprietary steps must therefore be taken to guard against this, as JavaScript does not support a native synchronisation mechanism.

 <!-- Example 1 - Using LoadStyleSheet -->

 <html>
    <head>
       <script type = "text/javascript">

       function LoadStyleSheet (StyleSheetURL) { ... }

       function OnClick ()
          {
          LoadStyleSheet ("MyStylesheet.css");

          ...

          }

       </script>
    </head>

    <body onclick = "OnClick ()"> ... </body>

 </html>
            
Copyright © Dodeca Technologies Ltd. 2007