JavaScript includes and namespaces -- an iframe hack

itub on 2005-04-11T18:51:25

I read with great interest schwern's thread about JavaScript's lack of includes and namespaces. A common answer for the include problem is that you can include your JavaScript "modules" via HTML like this:


but the problem, as Schwern pointed out, is that if module1.js wants to include module2.js, the user has to include both in HTML-space, which breaks encapsulation.

Sean Burke came up with a solution which addresses the problem by first loading a bootstrapping script, bootstrap.js.

I decided to try a different hack in HTML, by using hidden iframes. First, a disclamer: this was a quick hack, so it is certainly not perfect, and I wouldn't be surprised if someone invented it before, but I came up with this on my own. ;-) Let's see how it works. First, in test.html:




module1.my_func()

module1.module2.my_func()

Then, in module1.html:




And in module2.html:

To summarize:

  • iframe is used as the equivalent of an include statement
  • The JS code resides in HTML files, which may have further iframes for including more code.
  • The "namespaces" (i.e., the frames) get nested: when module1 includes module2, module2 can be accessed from the "main package" as module1.module2. This may be problematic if two different modules (say, module1a and module1b) include the same module (say, module2), because then module2 would be included twice and have two different "namespaces": module1a.module2 and module1b.module2.
  • Another caveat is that it requires support for iframes and CSS. If the user disables CSS, an ugly empty frame will be shown (perhaps it can also be hidden by changing it size via HTML attributes, but I didn't try that).