[Javascript] Including additional javascript files
Andrew Clover
and-babble at doxdesk.com
Tue Apr 5 06:07:17 CDT 2005
Alex Robinson <latechjavascript at alex.cloudband.com> wrote:
> The method does have two down sides.
Two more downsides:
3. It has to be done at page parse-time, can't include scripts after the
document is loaded.
4. The src attribute being written is relative to the page, not the
script, so a script 'a.js' wanting to include 'b.js' which lives in the
same directory has to either know its own relative path, or do some
nasty not-entirely-cross-browser-compatible DOM-sniffing to find out its
path from the preceding <script> tag.
> (though why the hell doesn't javascript have includes as part of
> the core?)
Quite agree. Seems an obvious omission.
> The fix for that situation I guess is would be to return to the idea I
> mentioned before of inserting the script element via the DOM.
I've had mixed results doing this across browsers too. ISTR on one
browser just creating the <script> and adding the src attribute was
enough to get the script run, whereas elsewhere the script was executed
when the element was appended to an element in the document, or it just
didn't do anything. It also seems a bit weird, doing document
manipulations in order to cause JS to run... what should happen when
<script> elements are moved or removed, and then added back in... and so
on. It's rather confusing - no wonder browsers behave inconsistently.
The only other approach I can immediately think of is to do an
XMLHttpRequest to get a script as text back from the server, and then
eval() it to run. Again, relying on XMLHttpRequest also rather shuts out
many browsers though.
Proper modular JavaScript files still seem just out of reach.
> Last observation is that some browsers halt execution of the current js
> file while loading the next one and others carry on regardless.
Really, what browser? This *should* be consistent as the behaviour of
document.write() has been defined back to
Netscape/someoldversion.mumble. The including script should run up to
the end of its own <script> block, then the browser will pause parsing
the page at the new document.written <script> block. I believe the
including script can still execute stuff from events or timeouts while
waiting for the included script to download, but once it does download
it should be executed all at once, excluding the including script until
it's finished.
--
Andrew Clover
mailto:and at doxdesk.com
http://www.doxdesk.com/
More information about the Javascript
mailing list