Client-side JavaScript
Encyclopedia
Client-side JavaScript (CSJS) is JavaScript
JavaScript
JavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions. It is a multi-paradigm language, supporting object-oriented, imperative, and functional programming styles....

 that runs on the client-side
Client-side
Client-side refers to operations that are performed by the client in a client–server relationship in a computer network.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 this way, the term was coined because the language is no longer limited to just client-side, since server-side JavaScript
Server-side JavaScript
Server-side JavaScript refers to JavaScript that runs on the server-side. This term was coined because the language is predominantly used on the client-side, i.e. client-side JavaScript ....

 (SSJS) is now available.

Environment

The most common Internet media type
Internet media type
An Internet media type, originally called a MIME type after MIME and sometimes a Content-type after the name of a header in several protocols whose value is such a type, is a two-part identifier for file formats on the Internet.The identifiers were originally defined in RFC 2046 for use in email...

 attribute for JavaScript source code is text/javascript, which follows HTML 4.01 and HTML 5
HTML 5
HTML5 is a language for structuring and presenting content for the World Wide Web, and is a core technology of the Internet originally proposed by Opera Software. It is the fifth revision of the HTML standard and is still under development...

 specifications and is supported by all major browsers. In 2006, application/javascript was also registered, though Internet Explorer
Internet Explorer
Windows 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. It was first released as part of the add-on package Plus! for Windows 95 that year...

 versions 6
Internet Explorer 6
Internet Explorer 6 is the sixth major revision of Internet Explorer, a web browser developed by Microsoft for Windows operating systems...

 through 8
Internet Explorer 8
Windows Internet Explorer 8 is a web browser developed by Microsoft in the Internet Explorer browser series. The browser was released on March 19, 2009 for Windows XP, Windows Server 2003, Windows Vista, Windows Server 2008, and Windows 7. Both 32-bit and 64-bit builds are available...

 do not recognize scripts with this attribute. When no type attribute is specified in a script tag, the type value is by default "text/javascript" per HTML 5 specification.

To embed JavaScript code in an HTML
HTML
HyperText Markup Language is the predominant markup language for web pages. HTML elements are the basic building-blocks of webpages....

 document, it must be within a element.



In the 1990s and early 2000s, HTML comment marks within the tags (<!-- ... -->) was sometimes required to ensure that the code was not rendered as text by old browsers that did not recognize the tag at all. The deprecated
Deprecation
In the process of authoring computer software, its standards or documentation, deprecation is a status applied to software features to indicate that they should be avoided, typically because they have been superseded...

 HTML attribute language="javaScript" was also required for some such browsers.

JavaScript in XHTML
XHTML
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....

 and XML
XML
Extensible Markup Language is a set of rules for encoding documents in machine-readable form. It is defined in the XML 1.0 Specification produced by the W3C, and several other related specifications, all gratis open standards....

 documents should be in XML CDATA
CDATA
The 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, as follows



(A double-slash // at the start of a line marks a JavaScript comment, which prevents the <![CDATA[ and ]]> from being parsed by the script.)

It is best practice for various reasons to reference JavaScript in external script files, e.g.:




To write valid HTML 4.01, the web server should return a 'Content-Script-Type' with value 'text/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 program
Hello world program
A "Hello world" program is a computer program that outputs "Hello world" on a display device. Because it is typically one of the simplest programs possible in most programming languages, it is by tradition often used to illustrate to beginners the most basic syntax of a programming language, or to...

.

This is the easiest method for a Hello world program that involves using popular browsers' support for the javascript URI scheme
URI scheme
In the field of computer networking, a URI scheme is the top level of the Uniform Resource Identifier naming structure. All URIs and absolute URI references are formed with a scheme name, followed by a colon character , and the remainder of the URI called the scheme-specific part...

 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 HTML
HTML
HyperText Markup Language is the predominant markup language for web pages. HTML elements are the basic building-blocks of webpages....

 forms which can be accessed through the HTML DOM
Document Object Model
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...

.
However there are also some very simple means of communicating with the user:
  • Alert dialog box
    Alert dialog box
    An alert dialog is a colloquial term for a particular type of dialog box that occurs in a graphical user interface. It is also known as an alert box, alert window, error dialog, alert popup or plainly alert.The typical alert dialog provides information in a separate box to the user, after which...

  • Confirm dialog box
    Dialog box
    In a graphical user interface of computers, a dialog box is a type of window used to enable reciprocal communication or "dialog" between a computer and its user. It may communicate information to the user, prompt the user for a response, or both...

    , prompt dialog box
  • Status bar
    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
    - Computing 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 event
Event-driven programming
In 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 handler is registered. These event handler functions are often defined as anonymous functions directly within the element node.

See also DOM Events
DOM Events
DOM 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 Events
XML Events
In 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

Most incompatibilities are not JavaScript issues but Document Object Model
Document Object Model
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...

 (DOM) specific. The JavaScript implementations of the most popular web browsers usually adhere to the ECMAScript
ECMAScript
ECMAScript is the scripting language standardized by Ecma International in the ECMA-262 specification and ISO/IEC 16262. The language is widely used for client-side scripting on the web, in the form of several well-known dialects such as JavaScript, JScript, and ActionScript.- History :JavaScript...

 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 Mozilla
Mozilla
Mozilla is a term used in a number of ways in relation to the Mozilla.org project and the Mozilla Foundation, their defunct commercial predecessor Netscape Communications Corporation, and their related application software....

 family of browsers (Mozilla
Mozilla
Mozilla is a term used in a number of ways in relation to the Mozilla.org project and the Mozilla Foundation, their defunct commercial predecessor Netscape Communications Corporation, and their related application software....

, Firefox
Mozilla Firefox
Mozilla Firefox is a free and open source web browser descended from the Mozilla Application Suite and managed by Mozilla Corporation. , Firefox is the second most widely used browser, with approximately 25% of worldwide usage share of web browsers...

 and Netscape Navigator
Netscape Navigator
Netscape Navigator was a proprietary web browser that was popular in the 1990s. It was the flagship product of the Netscape Communications Corporation and the dominant web browser in terms of usage share, although by 2002 its usage had almost disappeared...

) use JavaScript, Microsoft Internet Explorer uses JScript, and other browsers such as Opera
Opera (web browser)
Opera is a web browser and Internet suite developed by Opera Software with over 200 million users worldwide. The browser handles common Internet-related tasks such as displaying web sites, sending and receiving e-mail messages, managing contacts, chatting on IRC, downloading files via BitTorrent,...

 and Safari
Safari (web browser)
Safari is a web browser developed by Apple Inc. and included with the Mac OS X and iOS operating systems. First released as a public beta on January 7, 2003 on the company's Mac OS X operating system, it became Apple's default browser beginning with Mac OS X v10.3 "Panther". Safari is also the...

 use other ECMAScript implementations, often with additional nonstandard properties to allow compatibility
Compatibility
Compatibility may refer to:* Astrological compatibility* Compatibilism – a philosophical position* Compatibility * Compatibility * Compatibility * Electromagnetic compatibility* Interpersonal compatibility-Computing:...

 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 Microsoft
Microsoft
Microsoft Corporation is an American public multinational corporation headquartered in Redmond, Washington, USA that develops, manufactures, licenses, and supports a wide range of products and services predominantly related to computing through its various product divisions...

'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.
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
Browser sniffing
Browser sniffing is a technique used in websites and web applications in order to determine the web browser a visitor is using, and to serve browser-appropriate content to the visitor. This practice is sometimes utilized to circumvent incompatibilities between browsers in areas such as the...

and object detection. When there were only two browsers that had scripting capabilities (Netscape Navigator and Microsoft 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 setImageSource(imageName, imageUrl) {
// a test to discern if the 'document' object has a property called 'images'
// which value type-converts to boolean true (as object references do)
if (document.images) {
// only executed if there is an 'images' collection
document.images[imageName].src = imageUrl;
}
}


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 evaluation
Minimal evaluation
Short-circuit evaluation, minimal evaluation, or McCarthy 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...

.

Today, a combination of browser sniffing, object detection, and reliance on standards such as the ECMAScript specification and Cascading Style Sheets
Cascading Style Sheets
Cascading 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

  • JavaScript syntax
    JavaScript syntax
    The syntax of JavaScript is the set of rules that define a correctly structured JavaScript program.The examples below make use of the alert function for standard text output. The JavaScript standard library lacks an official standard text output function...

  • Bookmarklet
    Bookmarklet
    A bookmarklet is Unobtrusive JavaScript 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, however, an applet is not to be confused with a bookmarklet just as JavaScript is not to be confused with Java...

  • Document Object Model
    Document Object Model
    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...

     (DOM)
  • Comparison of JavaScript frameworks
    Comparison of JavaScript frameworks
    - Rationale :There are many JavaScript frameworks available. The intention of this comparison is to show some examples of JavaScript frameworks with their different features.- Table of Javascript Frameworks :- External links :* * * * * * * *...

  • SWFObject
    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 Flash
    Adobe Flash
    Adobe Flash is a multimedia platform used to add animation, video, and interactivity to web pages. Flash is frequently used for advertisements, games and flash animations for broadcast...

    content into webpages.

Resources


Libraries


Tools


Cooperation with

The source of this article is wikipedia, the free encyclopedia.  The text of this article is licensed under the GFDL.
 
x
OK