Dynamically Loading JavaScript Files


var s = document.createElement("script"); 

Sometimes it is necessary to load JavaScript code on demand, while a site is running. For instance, depending on user input, a specific external JavaScript file must be loaded.

One attempt is to use document.write() to dynamically add a new <script> element to the page. However, this fails with some browsers and also is not considered good style. A much better solution is to use DOM. First, you create a new <script> element and set the appropriate attributes. Then, you add this element to the page's DOM (see Chapter 5). Usually, the code is put in the <head> section of the page. The following listing shows the complete code; note that there actually is a <head> element so that the code works. Figure 1.2 shows the result of this code.

Dynamically Adding a Script (scriptdynamic.html)

<html> <head> <title>JavaScript</title> </head> <body> <script language="JavaScript"   type="text/javascript">   var s = document.createElement("script");   s.setAttribute("type", "text/javascript");   s.setAttribute("language", "JavaScript");   s.setAttribute("src", "script.js");   document.getElementsByTagName("head")[0].appendChild(s); </script> </body> </html> 

Figure 1.2. The modal window comes from the external file that was dynamically loaded.





JavaScript Phrasebook(c) Essential Code and Commands
JavaScript Phrasebook
ISBN: 0672328801
EAN: 2147483647
Year: 2006
Pages: 178

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net