Client-side JavaScript (
CSJS) is
JavaScriptJavaScript is an object-oriented scripting language used to enable programmatic access to objects within both the client application and other applications. It is primarily used in the form of client-side JavaScript, implemented as an integrated component of the web browser, allowing the...
that runs on
client-sideIn computer networking, the term client-side refers to operations that are performed by the client in a client-server relationship.Typically, a client is a computer application, such as a web browser, that runs on a user's local computer or workstation and connects to a server as necessary...
. While JavaScript was originally created to run on client-side, this term was coined because the language is no longer limited to just client-side, e.g.
server-side JavaScriptServer-side JavaScript refers to JavaScript that runs on server-side. This term was coined because the language is predominantly used on the client-side, i.e...
(SSJS) is also available.
Environment
The
Internet media typeMultipurpose Internet Mail Extensions is an Internet standard that extends the format of e-mail to support:* Text in character sets other than ASCII* Non-text attachments* Message bodies with multiple parts...
for JavaScript source code is
application/javascript, which was registered in 2006 but is not supported by all major browsers.
Internet ExplorerWindows Internet Explorer , is a series of graphical web browsers developed by Microsoft and included as part of the Microsoft Windows line of operating systems starting in 1995...
ignores scripts with the attribute
type="application/javascript". The HTML 4.01 and
HTML 5HTML5 is the next major revision of HTML , the core markup language of the World Wide Web. The Web Hypertext Application Technology Working Group started work on the specification in June 2004 under the name Web Applications 1.0.HTML5 is the proposed next standard for HTML 4.01, XHTML 1.0 and DOM...
specifications mention the unregistered
text/javascript, which is supported by all major browsers and is more commonly used.
To embed JavaScript code in an
HTMLHTML, which stands for Hyper Text Markup Language, is the predominant markup language for web pages. It provides a means to create structured documents by denoting structural semantics for text such as headings, paragraphs, lists etc as well as for links, quotes, and other items. It allows images...
document, it must be preceded with:
Older browsers typically require JavaScript to begin with:
The
<!-- ...
--> comment markup is required in order to ensure that the code is not rendered as text by very old browsers which do not recognize the
<script> tag in HTML documents (although
script-tags contained within the
head-tag will never be rendered, thus the comment markup is not always necessary), and the LANGUAGE attribute is a
deprecatedIn computer software standards and documentation, the term deprecation is applied to software features that are superseded and should be avoided. Although deprecated features remain in the current version, their use may raise warning messages recommending alternate practices, and deprecation may...
HTML attribute which may be required for old browsers. However,
<script> tags in
XHTMLExtensible Hypertext Markup Language, or XHTML, is a family of XML markup languages that mirror or extend versions of the widely used Hypertext Markup Language , the language in which web pages are written....
/
XMLXML is a set of rules for encoding documents electronically. It is defined in the produced by the W3C and several other related specifications; all are fee-free open standards....
documents will not work if commented out, as conformant XHTML/XML parsers ignore comments and also may encounter problems with
--,
< and
> signs in scripts (for example, the integer decrement operator and the comparison operators). XHTML documents should therefore have scripts included as XML
CDATAThe term CDATA, meaning character data, is used for distinct, but related purposes in the markup languages SGML and XML. The term indicates that a certain portion of the document is general character data, rather than non-character data or character data with a more specific, limited...
sections, by preceding them with
(A double-slash
// at the start of a line marks a JavaScript comment, which prevents the
<![CDATA[ and
]]> from being parsed by the script.)
The easiest way to avoid this problem (and also as a best practice) is to use external script, e.g.:
Historically, a non-standard (non-W3C) attribute
language is used in the following context:
HTML elements
http://www.w3.org/TR/html4/interact/scripts.html#h-18.2.3 may contain intrinsic events to which you can associate a script handler.
To write valid HTML 4.01, the web server should return a 'Content-Script-Type' with value 'application/javascript'. If the web server cannot be so configured, the website author can optionally insert the following declaration for the default scripting language in the header section of the document.
Hello World example
For an explanation of the tradition of programming "Hello World", as well as alternatives to this simplest example, see
Hello world programA "Hello World" program is a computer program which prints out "Hello, world!" on a display device. It is used in many introductory tutorials for teaching a programming language. Such a program is typically one of the simplest programs possible in a computer language...
.
This is the easiest method for a Hello world program that involves using popular browsers' support for the virtual 'javascript' protocol to execute JavaScript code. Enter the following as an Internet address (usually by pasting into the address box):
javascript:alert('Hello, world!');
User interaction
Most interaction with the user is done by using
HTMLHTML, which stands for Hyper Text Markup Language, is the predominant markup language for web pages. It provides a means to create structured documents by denoting structural semantics for text such as headings, paragraphs, lists etc as well as for links, quotes, and other items. It allows images...
forms which can be accessed through the HTML
DOMThe Document Object Model is a cross-platform and language-independent convention for representing and interacting with objects in HTML, XHTML and XML documents. Aspects of the DOM may be addressed and manipulated within the syntax of the programming language in use...
.
However there are also some very simple means of communicating with the user:
- Alert dialog box
An alert dialog is a colloquial term for a particular type of dialog box that occurs in a graphical user interface...
- Confirm dialog box
In graphical user interfaces, a dialog box is a special window, used in user interfaces to display information to the user, or to get a response if needed. They are so-called because they form a dialog between the computer and the user—either informing the user of something, or requesting...
, prompt dialog box
- Status bar
A status bar, similar to a status line, is an information area typically found at the bottom of windows in a graphical user interface.A status bar is sometimes divided into sections, each of which shows different information. Its job is primarily to display information about the current state of...
- Console
Console may be:In ' and video games:* System console, a physical device to operate a computer** Virtual console, a user interface for multiple computer consoles on one device** Command-line interface, the typical use of the computer console...
Events
Element nodes may be the source of various
eventIn computer programming, event-driven programming or event-based programming is a programming paradigm in which the flow of the program is determined by events—i.e., sensor outputs or user actions or messages from other programs or threads.Event-driven programming can also be defined as an...
s which can cause an action if a JavaScript
event handlerIn computer programming, an event handler is an asynchronous callback subroutine that handles inputs received in a program. Each event is a piece of application-level information from the underlying framework, typically the GUI toolkit. GUI events include key presses, mouse movement, action...
is registered. These event handler functions are often defined as anonymous functions directly within the element node.
See also
DOM EventsDOM events allow event-driven programming languages like JavaScript, JScript, ECMAScript, VBScript and Java to register various event handlers/listeners on the element nodes inside a DOM tree, e.g. HTML, XHTML, XUL and SVG documents....
and
XML EventsIn computer science and web development, XML Events is a W3C standard for handling events that occur in an XML document. These events are typically caused by users interacting with the web page using a device such as a web browser on a personal computer or mobile phone.- Formal Definition :An XML...
.
Incompatibilities
Note: Most incompatibilities are not JavaScript issues but
Document Object ModelThe Document Object Model is a cross-platform and language-independent convention for representing and interacting with objects in HTML, XHTML and XML documents. Aspects of the DOM may be addressed and manipulated within the syntax of the programming language in use...
(DOM) specific. The JavaScript implementations of the most popular web browsers usually adhere to the
ECMAScriptECMAScript is a scripting language, standardized by Ecma International in the ECMA-262 specification and ISO/IEC 16262. The language is widely used on the web, especially in the form of its three best-known dialects, JavaScript, ActionScript, and JScript.-History:JavaScript was originally developed...
standard, such that most incompatibilities are part of the DOM implementation. Some incompatibility issues that exist across JavaScript implementations include the handling of certain primitive values like "undefined", and the availability of methods introduced in later versions of ECMAScript, such as the .pop, .push, .shift, and .unshift methods of arrays.
JavaScript, like HTML, is often not compliant to standards, instead being built to work with specific web browsers. The current ECMAScript standard should be the base for all JavaScript implementations in theory, but in practice the
MozillaMozilla is a term used in a number of ways in relation to the now-defunct Netscape Communications Corporation and its related application software, including the Mozilla.org group and its successor the Mozilla Foundation....
family of browsers (
MozillaMozilla is a term used in a number of ways in relation to the now-defunct Netscape Communications Corporation and its related application software, including the Mozilla.org group and its successor the Mozilla Foundation....
,
FirefoxMozilla Firefox is a free and open source web browser descended from the Mozilla Application Suite and managed by Mozilla Corporation. Firefox has 23.75% of the recorded usage share of web browsers , making it the second most popular browser in terms of current use worldwide after Microsoft's...
and
Netscape NavigatorNetscape Navigator and Netscape are the names for the proprietary web browser popular in the 1990s, and the flagship product of the Netscape Communications Corporation, and the dominant web browser in terms of usage share. Yet by 2002 its users had almost disappeared...
) use
JavaScript, Microsoft Internet Explorer uses
JScript, and other browsers such as
OperaOpera is a web browser and internet suite developed by the Opera Software company. The browser handles common Internet-related tasks such as displaying websites, sending and receiving e-mail messages, managing contacts, IRC online chatting, downloading files via BitTorrent, and reading web feeds...
and
SafariSafari is a web browser developed by Apple Inc. First released as a public beta on 7 January 2003 on the company's Mac OS X operating system, it became Apple's default browser beginning with Mac OS X v10.3 "Panther". Apple has also made Safari the native browser for the iPhone OS...
use other
ECMAScript implementations, often with additional nonstandard properties to allow
compatibilityThe term compatibility may refer to:* In biology:** Blood type compatibility* In computing:** Pin-compatibility** Computer compatibility*** Backward compatibility*** Forward compatibility* It may also refer to:** Astrological compatibility...
with JavaScript and JScript.
JavaScript and JScript contain several properties which are not part of the official ECMAScript standard, and may also miss several properties. As such, they are in points incompatible, which requires script authors to work around these bugs. JavaScript is more standards-compliant than
MicrosoftMicrosoft Corporation is a multinational computer technology corporation that develops, manufactures, licenses, and supports a wide range of software products for computing devices...
's JScript, which means that a script file written according to the ECMA standards is less likely to work on browsers based on Internet Explorer. However, since there are relatively few points of nonconformance, this is very unlikely.
This also means every browser may treat the same script differently, and what works for one browser may fail in another browser, or even in a different version of the same browser. As with HTML, it is thus advisable to write standards-compliant code.
Combating incompatibilities
There are two primary techniques for handling incompatibilities:
browser sniffing and
object detection. When there were only two browsers that had scripting capabilities (Netscape and Internet Explorer), browser sniffing was the most popular technique. By testing a number of "client" properties, that returned information on computer platform, browser, and versions, it was possible for a scripter's code to discern exactly which browser the code was being executed in. Later, the techniques for
sniffing became more difficult to implement, as Internet Explorer began to "spoof" its client information, that is, to provide browser information that was increasingly inaccurate (the reasons why Microsoft did this are often disputed). Later still, browser sniffing became something of a difficult art form, as other scriptable browsers came onto the market, each with its own platform, client, and version information.
Object detection relies on testing for the existence of a property of an object.
function set_image_source ( imageName, imageURL )
{
if ( document.images ) // a test to discern if the 'document' object has a property called 'images' which value type-converts to boolean true (as object references do)
{
document.images[imageName].src = imageURL; // only executed if there is an 'images' collection
}
}
A more complex example relies on using joined boolean tests:
if ( document.body && document.body.style )
In the above, the statement "
document.body.style" would ordinarily cause an error in a browser that does not have a "
document.body" property, but using the boolean operator "
&&" ensures that "
document.body.style" is never called if "document.body" doesn't exist. This technique is called
minimal evaluationShort-circuit evaluation or minimal evaluation denotes the semantics of some boolean operators in some programming languages in which the second argument is only executed or evaluated if the first argument does not suffice to determine the value of the expression: when the first argument of the...
.
Today, a combination of browser sniffing, object detection, and reliance on standards such as the ECMAScript specification and
Cascading Style SheetsCascading Style Sheets is a style sheet language used to describe the presentation semantics of a document written in a markup language...
are all used to varying degrees to try to ensure that a user never sees a JavaScript error message.
Frameworks
See also
- Bookmarklet
A bookmarklet is an applet, a small computer application, stored as the URL of a bookmark in a web browser or as a hyperlink on a web page. The term is a portmanteau of the terms bookmark and applet. Whether bookmarklet utilities are stored as bookmarks or hyperlinks, they are designed to add...
- DOM
The Document Object Model is a cross-platform and language-independent convention for representing and interacting with objects in HTML, XHTML and XML documents. Aspects of the DOM may be addressed and manipulated within the syntax of the programming language in use...
- Comparison of JavaScript frameworks
- External links :* * * * *...
- SWFObject
SWFObject is an open-source JavaScript library used to embed Adobe Flash content onto Web pages, which is supplied as one small JavaScript file...
, a JavaScript library used to embed Adobe FlashAdobe Flash is a multimedia platform originally acquired by Macromedia and currently developed and distributed by Adobe Systems. Since its introduction in 1996, Flash has become a popular method for adding animation and interactivity to web pages...
content into webpages.
Resources
Libraries
Tools
Cooperation with