AJAX - The Complete Reference

(avery) #1

PART IV


Appendix A: JavaScript Quick Reference 555


For inline inclusion of JavaScript within a markup document, some developers may
consider using an XHTML comment mask or even a CDATA section to hide the code from
user agents that do not understand it.

<script type="text/javascript">
<!--
alert("Can you run me Mr. Browser?");
//-->
</script>

However, it is generally considered better to avoid such approaches and externalize
JavaScript in .js files referenced by <script> tags.

Approach Example Notes
<script> tag
with inlined
code

<script type="text/javascript">
alert('hi');
</script>

The type attribute should be used
to indicate the type of script in use
as specified by a MIME type value.
By default, browsers will assume
JavaScript without this attribute.
Commonly, developers use the
nonstandard language attribute
instead because of tradition and
some flexibility in shielding code
from browsers not supporting
certain versions.
<script> tag
referencing
external file

<script src="lib.js" type=
"text/javascript"></script>

<script src=
"http://ajaxref.com/libs/libs.js"
type="text/javascript"></script>

Browsers should synchronously
fetch linked script code, though
some browsers may allow continued
parsing and asynchronous fetching
with the inclusion of a defer
attribute in the tag.

Inlined script
within (X)HTML
event handling
attributes

<p onclick="alert('hi');">
Should be able to click me?</p>

The scope of variables within attribute
handlers will be local to the handler if
defined with var. The tight coupling
between markup and script with this
method does not make the approach
highly maintainable.
javascript:
pseudo URLs
within links

<a href="javascript: alert('hi') ">
Click to trigger</a>

This approach does not degrade
well with script off and may induce
usability problems if an application/
page contains both script and
nonscript triggering links.

TABLE A-4 JavaScript Inclusion Methods
Free download pdf