spacer
Yehuda Shiran March 1, 2001
Indirect External File Loading
Tips: March 2001

Yehuda Shiran, Ph.D.
Doc JavaScript

Developer News
Microsoft Shows Off Silverlight 4, IE9 Plans
Metasploit Expands Vulnerability Test Framework
HyperCard Reborn?

Internet Explorer 5.5 and Netscape 6 differ from previous versions in the way they dynamically load external scripts. Here, the term "dynamic loading" refers to the case where you document.write the include statement on the fly. Suppose you have the following external script:

function printMessage() {
  alert("Hello from External");
}
and you want to dynamically load it from the main html code:

<SCRIPT LANGUAGE="JavaScript">
document.write('<SCRIPT LANGUAGE="JavaScript" SRC="010226b.js"><\/SCRIPT>');
</SCRIPT>

Now, suppose you want to call the printMessage() function in the main html program, immediately after loading the script:

<SCRIPT LANGUAGE="JavaScript">
document.write('<SCRIPT LANGUAGE="JavaScript" SRC="010226b.js"><\/SCRIPT>');
printMessage();
</SCRIPT>

Try it. You get an error message. The reason for this failure is that both Internet Explorer 5.5 and Netscape 6 do not wait for the external script to be read before continuing parsing the main script.

One of the remedies for this problem is to use indirection. Put a static include in your main program, and then write the dynamic loading command (document.write) in the included file. For example, put the following code in your main page:

<SCRIPT LANGUAGE="JavaScript" SRC="010301b.js"></SCRIPT>

In the file 010301b.js put the dynamic load command:

document.write('<SCRIPT LANGUAGE="JavaScript" SRC="010301c.js"><\/SCRIPT>');

Your main page should like like this now:

<SCRIPT LANGUAGE="JavaScript" SRC="010301b.js"></SCRIPT>
<SCRIPT LANGUAGE="JavaScript">
printMessage();
</script>

Check it out. You should get the alert message "Hello From External."


People who read this tip also read these tips:

Look for similar tips by subject:

internet.commediabistro.comJusttechjobs.comGraphics.com

Search:

WebMediaBrands Corporate Info

Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs

webref The latest from WebReference.com Browse >
Rolling Out Your Own HTML Application Version Control · HTML 5: Client-side Storage · Working with Ajax Server Extensions
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Wi-Fi Product Watch, November 2009 · Chip Market Recovering From '08 Collapse · Low-Cost Tools to Kickstart Your New Business