JavaScript Script Tags
The HTML script
tag is used to identify and run javaScript code.
- The browser reads each script tag in the order in which it appears in the document.
- The javascript defined by a script tag is compiled and run immediately after the tag is recognized by the browser.
- There is no limit to the number of script tags in a document.
- The same-origin policy prevents scripts hosted at other domains from running unless CORS has been setup.
NOTE: For older code:
type="text/javascript"
is required in the script tag in HTML 4 and XHTML, but optional in HTML5.CDATA
is needed for XHTML pages if the script has any HTML characters like<
and>
in it.<script>//<![CDATA[ ...code... //]]></script>
- 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.
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.
Inline
<script>/* JavaScript code here */</script>
Dynamic
script
tags can be dynamically created from running JavaScript.
<script>
document.write('\x3Cscript' + 'src="my_other_script.js">\x3C/script>');
</script>