How to use JavaScript in external files
by kalai[ Edit ] 2008-04-25 20:36:26
Well, first of all, you should not include any HTML in your JavaScript file. This means that you should not include things like <script type="text/javascript"><!-- or --></script> in the file. Those belong in the HTML file only.
Now, the exact same code should behave exactly the same whether it's included in the document or in a separate file. However, there is one issue you must be aware of with JavaScript files: If the JavaScript is placed in the head of the document, the files will be downloaded as soon as the HTML parser reaches them, and they will be executed as soon as they are finished downloading. This means that you can not rely on them being executed in the order they appear in the head. To get around this, you can make sure no code that should actually execute is present in the JavaScript file, only variable declarations and functions. Then you move the execution of code into the window.onload function where you can rely on all of the JavaScript files being referenced in the head to be loaded. Note that this goes only for scripts included in the head of the document, not scripts in the body of the document.