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)
Figure 1.2. The modal window comes from the external file that was dynamically loaded. |