Slash Boxes
NOTE: use Perl; is on undef hiatus. You can read content, but you can't post it. More info will be forthcoming forthcomingly.

All the Perl that's Practical to Extract and Report

use Perl Log In

Log In

[ Create a new account ]

itub (5708)


Pause ID: ITUB []
PerlMol []
AnnoCPAN []
POD Indexing Project []

Journal of itub (5708)

Monday April 11, 2005
01:51 PM

JavaScript includes and namespaces -- an iframe hack

[ #24130 ]
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:

<script src="module1.js"></script>

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:

<!-- include module1 -->
<iframe name="module1" src="module1.html" style="display:none"></iframe>

<p onclick="module1.my_func();">module1.my_func()</p>
<p onclick="module1.module2.my_func();">module1.module2.my_func()</p>

Then, in module1.html:

<!-- include module2 -->
<iframe name="module2" src="module2.html" style="display:none"></iframe>

<script type="text/javascript">
function my_func() {

And in module2.html:

<script type="text/javascript">
function my_func() {

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).
The Fine Print: The following comments are owned by whoever posted them. We are not responsible for them in any way.
More | Login | Reply
Loading... please wait.