Google

Load JavaScript



Including JavaScript Code


JavaScript code could be included two ways: 
either embedded into an HTML page, or in an external file.

embedded


<script type="text/javascript">
window.alert("Welcome to JavaScript!");
</script>


You can place this <script> element anywhere, and the code is will be executed after this part of the HTML page has been loaded .

External JavaScript Files

Relative URL :
<script language="JavaScript" type="text/javascript"   src="jquery.js"></script>  

Absolute URL :  

<script language="JavaScript"    type="text/javascript"    src="http://hostname/jquery.js"> </script>
The external file contains only the JavaScript code, no <script> elements . however, A <script> element is used to load the external file .
 The src attribute holds the URL of the external script , and could be relative or absolute URLs .

Dynamically Loading JavaScript Files

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 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 . Usually, the code is put in the <head> section of the page. The following shows the complete code; note that there actually is a <head> element so that the code works.


<script language="JavaScript" type="text/javascript">

var e = document.createElement("script");
e.setAttribute("type", "text/javascript");
e.setAttribute("language", "JavaScript");
e.setAttribute("src", "jquery.js");
document.getElementsByTagName("head")[0].appendChild(e);

</script>

No comments: