Search code examples
javascriptasp-classicprototypejs

Dynamically loading CSS and JavaScript using Prototype


I have a classic ASP application that I've been constantly trying to modularize. Currently, almost all pages are divided in to two pages:

  • an outer page that contains the layout, header, sidebar, footer
  • an inner page that contains ASP code

The outer pages use dreamweaver templates so updating layout and replicating changes is easy. The inner pages are managed by me. Now here is the problem:

I had to add a lightbox to one page, I chose Lightbox 2 which requires Prototype. I ended up adding Prototype on every page, assuming that sooner or later I'll upgrade all pages, forms, ajax requests and other javascript to use Prototype. I've now added two other plugins -- Modalbox and Protofade; each with a pair of .JS and .CSS files. Since I'll be using these three plugins on specific set of pages I am wondering if I can load the required CSS and JS files dynamically. I do not want to access the document head and add include files there (i.e. by bloating the <head> tag with about a dozen <script> and <link> tags), I'll have to do this from inside a DIV where all ASP code is supposed to go.


Solution

  • You can add scripts dynamically by adding script elements to the document; details and sample code on the this page from Unofficial Prototype & script.aculo.us wiki. E.g.:

    var element;
    var script;
    
    element = /* ...grab the element you want to add to; I'd use $$('head')[0] */;
    if (element) {
        script = new Element('script', { type: 'text/javascript', src: 'dynamic.js' });
        element.appendChild(script);
    }
    

    Adding stylesheet links should be essentially the same. Although that page has you adding to the head, you've said you don't want to do that (though I'm not clear why not, since you're doing it dynamically on the user's machine), but it should still work regardless of where you add them.