Script Tags

Inline

<script>/* JavaScript code here */</script>

Referenced

<script name="my_script" src="path/or/url/to/my_script.js"></script>
  • When referencing a file, no javascript code should be put inside the tag.
  • The name attribute is optional and is intended for humans only.

Dynamic

<script>
    document.write('\x3Cscript src="my_other_script.js">\x3C/script>');
</script>

You can dynamically create a script tag and run it.

Overview

The HTML script tag is used to identify and run javaScript code.

  • The javascript defined by a script tag is compiled and run immediately after the tag is recognized by the browser.
  • You can use as many script tags in a document as you feel necessary.
  • The browser reads each script tag in the order in which it appears in the document. If a script is defining functions or data that are used by another script, then the defining must be done before use. So the defining scripts must come before the using scripts.
  • type="text/javascript" is required in the script tag in HTML 4 and XHTML, but optional in HTML5.
  • Do not use the <!-- //--> hack with scripts. It was intended to prevent scripts from showing up as text on the first generation browsers Netscape 1 and Mosaic.
  • CDATA is needed for XHTML pages if the script has any HTML characters like < and > in it. <script>//<![CDATA[ ...code... //]]></script>
  • JS security ( Same-origin policy ) prevent scripts hosted at other domains from running unless you setup CORS.
 

More Resources