|
|
JavaScript Guidelines and Best Practice
You are here: irt.org | Articles | Design | JavaScript Guidelines and Best Practice Published on: Saturday 26th June 1999 By: Martin Webb
IntroductionREF [1] Netscape JavaScript, also called client side JavaScript (CSJS) allows a client browser to display HTML and execute JavaScript code resulting in a page that the user sees. JavaScript statements embedded in an HTML page can respond to user events such as mouse-clicks, form input, and page navigation. LiveWire JavaScript, also called server side JavaScript (SSJS) is an application development environment that uses JavaScript for creating server based applications similar to CGI (Common Gateway Interface) programs. JScript is Microsoft's implementation of JavaScript. Dynamic HTML (DHTML) is the combination of HTML, JavaScript, the Document Object Model (DOM) and Cascading Style Sheets (CSS). This document is primarily concerned with client side JavaScript or JScript. The general term JavaScript will be used through the remainder of this document to refer to both Netscape's JavaScript and Microsoft's JScript. JavaScript is not Java! JavaScript was developed independently of Java. It was originally being developed as a product called LiveScript, but was renamed when Netscape announced support for Java in Navigator 2.0. This marketing decision has been a bane on JavaScript ever since. IntroductionProblems unique to client side processingIn most programming languages, source code is compiled on one machine and then executed on the same machine or possibly on another. In either case, the resultant program will run on a known and stable environment. JavaScript source code is interpreted (or compiled) at the time it is used, by the computer it is being used on. When writing the JavaScript source code, it is difficult to predict exactly what hardware, operating system or browser will be used. This means that you cannot write JavaScript code expecting to use the latest methods and event handlers in JavaScript code and then expect it to run on all browsers currently in use, as some people will still be using browsers that only support JavaScript 1.0. Therefore it is necessary to either restrict ourselves to only those aspects of JavaScript available in JavaScript 1.0, or write code that degrades safely in browsers with a lower version of JavaScript code than that which is required. This problem does exist with other programming languages, but not to the extent to which JavaScript code is used on many web pages, on many web sites, all around the world, which can be viewed and processed on the client machine by anyone, anywhere in the world, using many different combinations of hardware platforms, operating systems and web browsers. Web pages are supposed to be truly universal. JavaScript code should aim to be as well. JavaScript StandardsThe European standards body, ECMA, released the 2nd edition of ECMA-262, the language specification derived from Netscape JavaScript 1.1, in June 1998. The ECMAScript language specification is available as a Microsoft Word document or as an Acrobat PDF file from the ECMA Web site - REF [2]. ECMA-262 has been adopted by the ISO/IEC JTC 1 as ISO/IEC 16262. Microsoft fully supports the specification through JScript 3.0, the scripting engine built into Microsoft Internet Explorer version 4.0 - REF [13]. Netscape fully supports the specification in JavaScript 1.3, supported in Netscape Navigator 4.06 and 4.5 - REF [14]. Netscape partially supports the specification in JavaScript 1.2, supported in Netscape Navigator 4.01 through to 4.05, with the exception of support for Unicode and the use of platform specific Date object handling - REF [19]. The ECMAScript is a language specification, and so in itself does not define the object model (beyond a small set of 'native objects'.) A Web browsers object model, or the Document Object Model (DOM), which is used by scripting languages is being standardised by the W3C - World Wide Web Consortium REF [12]. "The Document Object Model is a platform- and language-neutral interface that will allow programs and scripts to dynamically access and update the content, structure and style of documents." - W3C There are three DOM levels:
Online JavaScript DocumentationFor online documentation for the core JavaScript language then the recommended documentation is the browser vendors own documentation. For cross-vendor documentation other independent online documentation is recommended, for example irt.org - REF [5]. JavaScript BooksThere are two main books on JavaScript that developers should have access to: Also if possible the second edition of JavaScript the Definitive Guide - REF [8] - should be used as, due to its publication date, it covers mainly JavaScript 1.0 and 1.1, and doesn't cover JavaScript 1.2 used in Netscape Navigator 4 and Internet Explorer 4. Browsers with JavaScript SupportJavaScript support is present in:
Browsers without JavaScript SupportThere are several browsers that do not have support for JavaScript, and are likely to remain so indefinitely:
and others. JavaScript VersionsThere are probably at least two dozen versions of JavaScript in use today. The following table details the main JavaScript versions used by the two major browser vendors:
* The JavaScript engine within Microsoft's Internet Explorer can be updated independently of the browser version - REF [15]. JScript 2.x is the version used in Microsoft Internet Information Server 1.0. JScript 4.x is the version used in Microsoft Visual Studio 6.0. There are also differences in the versions depending on the platform the browser is used on. The Mac, for example, suffers many incomplete or buggy versions of JavaScript on Microsoft Internet Explorer. Disabling and Enabling JavaScriptIt is possible for JavaScript to be disabled on the client browser: Netscape Navigator 3:Options -> Network Preferences -> Languages -> Enable JavaScript Netscape Navigator 4:Edit -> Preferences -> Advanced -> Enable JavaScript Microsoft Internet Explorer 3:Edit -> Options -> Security -> Custom -> Active Scripting -> Disable Microsoft Internet Explorer 4:View -> Options -> Security -> Custom -> Active Scripting -> Disable Microsoft Internet Explorer 5:Tools -> Options -> Security -> Custom -> Active Scripting -> Disable When using JavaScript, it is important to test your site with JavaScript disabled to ensure that your site is still accessible without JavaScript. PortabilityWhen developing client side processing using JavaScript, even when writing code for a specific browser used inside an Intranet it is important to consider the portability of the JavaScript code, in the event that the company moves to a different browser vendor in the future. JavaScript ToolsThere are several third party vendor JavaScript tools - some of which are listed on Netscape's Technical JavaScript site - REF [9]. There are also the following JavaScript tool's available from Netscape: There are also JavaScript tool's available from Microsoft: The use of JavaScript Tools is subject to the approval of the ITVoice product approval process - REF [16]. The FutureThe near future will see embedded web client software within Internet Screen Phones, Multimedia Kiosks and Personal Digital Assistant's. These technologies may or may not provide JavaScript support. It is essential that Web sites and pages can be accessed by client software that is not JavaScript enabled - REF [17] and REF [18]. JavaScript GuidelinesObjectsJavaScript can control a hierarchy of objects within the Document Object Model:
The above diagram details the hierarchy of objects available in JavaScript 1.0, 1.1 and 1.2. There are several points to be aware of when accessing the objects:
Browser support for all these objects should be detected for, before attempting to access their properties. To detect for browser support of an object, the following generic approach should be taken:
This allows a small amount of future proofing for when later browser versions provide additional object support. Most objects within the Document Object Model are attached to a hierarchy of objects, with the top most object being the current window. For example, the frames object can be accessed as window.frames[ ], whereas the forms object can be accessed as document.forms[ ]. The documents object is also accessed as window.document, so in the previous example the full hierarchy is actually window.document.forms[ ], however it is perfectly acceptable to omit the reference to the window object. Object PropertiesObject properties do not always require the complete object hierarchy to be stated, for example, window.location.href is equivalent to location.href, as most objects come under the window object the use of the window reference is optional. Not all object properties are available in all versions of JavaScript. Check the documentation before making use of an object property. If you cannot restrict yourself to the object properties available in JavaScript 1.0, then ensure that your code does not get executed by a browser without support for the object property you are using. Browser vendors are constantly improving their implementations of JavaScript, following customer feedback, the introduction of the ECMAScript standard, the release of recommendation documents from the W3C and the need to keep ahead of/up with the competition. Object MethodsAs with properties, not all methods are supported by all browsers. Check the documentation before making use of an object method. If you cannot restrict yourself to the object methods available in JavaScript 1.0, then ensure that your code does not get executed by a browser without support for the object method you are using. Beware, that although the method may be supported by certain versions of JavaScript, that support may not be universal across all platforms. As before, it is possible to omit the window reference when using window methods, e.g. alert('Hello world'). However, there are certain occasions where omitting the window reference should be avoided, for example, when using the open() method, as both the document and window objects have a window method. it is important to specify in detail the correct object hierarchy in these circumstances, e.g. window.open() or document.open(). Events and Event HandlersThere are an increasing number of events and event handlers being introduced in each browser release, fortunately due to the way that HTML attributes are ignored if not recognised it is possible to include event handlers that are not supported by all browsers, for example, the following although syntactically correct, will not cause a JavaScript error message, and will never actually cause the enclosed JavaScript code to be executed (unless of course kettles start to have embedded JavaScript code):
It is however important to realise that JavaScript code is case sensitive, despite the case insensitive implementation of Microsoft Internet Explorer 3. Therefore the case of event handlers must be correct, or there is a danger that browsers will not recognise them, for example, onMouseover is incorrect, whereas onMouseOver is correct. It is also important to note that JavaScript event handlers form part of the HTML tag attributes, and as such, should be valid event handlers as defined within the HTML 4.0 Specification REF [26] and the associated HTML 4.0 Document Type Definition (DTD) REF [27]. Invalid event handlers might cause problems with a future browser release. JavaScript Best PracticeThe following demonstrate the practices that should be followed when writing JavaScript code. It is based on the authors use and knowledge of JavaScript over several years practical experience. Inline JavaScript source codeAny JavaScript code that does not write out to the document should be placed within the head of the document:
This ensures that the JavaScript function definitions have been loaded by the browser before it is required. It also makes it slightly easier to maintain the JavaScript code if it can always be found in the head of the document. Other potential locations for JavaScript code include: Event Handlers:
Links (however see the guideline on the usage of JavaScript Links):
Source files (however see the guideline on the usage of JavaScript Source Files):
JavaScript Entities (however see the guideline on the usage of JavaScript Entities):
The JavaScript language versionIf you require a certain version of JavaScript then specify the version as part of the language attribute:
If you require access to object properties and methods of core JavaScript not available in all versions of JavaScript, provide different function definitions for the relevant JavaScript versions:
As a minimum specify the LANGUAGE="JavaScript" attribute to avoid any possible conflict with any other client side processing language, e.g. VBScript. Hiding JavaScript source code from the browserAlways wrap inline JavaScript code within comment tags to hide the JavaScript from older non JavaScript aware browsers:
or:
or:
This does not stop the JavaScript source code from being displayed from the user if they view the document source, but it does stop the JavaScript code from being displayed on the page in old browser versions released before JavaScript was developed. Actually hiding JavaScript code from the user is impossible - you can make it harder by hiding the code in other frames or in JavaScript Source files. In Internet Explorer 5, there is an encryption facility that allows JavaScript source code and HTML to be encrypted prior to being paced on a publicly accessible web server - REF [20]. In order for Internet Explorer to be able to parse the encrypted JavaScript code, it must be able to decrypt it, so another program could be written to decrypt it and display it, instead of decrypt it and run it. It should therefore not be regarded as a secure means of protecting JavaScript source code. The resultant encrypted code is not supported by Netscape and should therefore be avoided. Commenting JavaScript and HTML codeAdd comments to your code to aid maintenance. The characters <!-- signify the start of a comment in HTML. The characters -- followed by > signify the end of an HTML comment. It is therefore important not to use the characters -- within either HTML or JavaScript unless used as part of an HTML comment, as browsers may not always interpret and render the HTML as you might expect. It is important that the double forward slashes appear before the --> characters, as on their own the --> characters are not JavaScript comment characters. Comments in JavaScript can be started with either the characters // which signifies a comment up to the end of the current line (or until terminated by a HTML end comment -->), or with the use of a starting /* and an ending */ which marks everything between these two sets of characters as a JavaScript comment. The following is incorrect:
as on its own --> is not a valid JavaScript comment tag. The following is correct:
Semi-colonsTo avoid confusion always end single JavaScript statements with a semi-colon. The following demonstrates confusion that might arise is semi-colons are missed off:
Returns equal if A equals B.
Always returns equal, even if A does not equal B.
Returns nothing if A equals B, as the return statement does not extend onto the next line. This will actually result in an error. Although there is no need to end a block statement with a semicolon, it is recommended that one is included:
Double and Single QuotesUse double quotes (") for HTML attributes and single quotes (') for JavaScript string literals. When writing HTML it is general practice to use double quotes for tag attributes, e.g.:
When writing JavaScript it is general practice to use single quotes for string literals:
In general these quoting styles then complement one another when outputting HTML using JavaScript:
Where nested quotes are required then use the escape key ("\") to escape the quotes:
Scripting HTML tagsWhen outputting HTML using JavaScript always escape the forward slash ('/') by placing a backward slash ('\') in front of it. Do not use:
Use:
Some browsers can mistakenly identify the forward slash as the end of the JavaScript source code. Placing the backward slash in front of each forward slash 'escapes' the forward slash character and avoids this problem. The NOSCRIPT tagUse the NOSCRIPT tag to provide alternative text for JavaScript disabled browsers:
The HTML within the NOSCRIPT tags is only rendered if the browser recognises the NOSCRIPT tag but does not support JavaScript. Older browser versions will not recognise either, but will only render the output in between the NOSCRIPT tags, as any JavaScript code will have been placed within a HTML comment. Image SwappingAlways check for the existence of the image object before attempting to access any image properties:
Use this technique rather then attempting to test for the browser type and version. Always use the name of the image rather than its index number. Image swapping within tables using the index number is unreliable. Images currently outside of tables may not always remain so. JavaScript within TablesAlways output the entire table row using JavaScript. Some browsers display a corrupt segment of your JavaScript code in front of the table, and then do not execute the JavaScript code. Do not use:
Instead use:
Frame DetectionDo not rely on the document being loaded within a Frameset, check first before executing JavaScript code held in a parent or sibling frame:
JavaScript LinksAvoid using the javascript: protocol as a default URL within a link. If JavaScript is disabled then the link will not work. Do not use:
Instead use JavaScript itself to override the href property of the link:
This approach then allows graceful degradation to a default page, and can be used to hide JavaScript intensive pages:
The javascript: protocol although not part of any URI (Uniform Resource Identifiers) RFC (Request For Comments), is supported in JavaScript enabled browsers REF [28]. Avoid using void()The void() function is not supported by all browsers. Create your own void function. The in built void() function is supported since JavaScript 1.1, therefore it is best to create your own void function rather than rely on JavaScript 1.1 being available:
JavaScript PerformanceAvoid writing output multiple times to the document, concatenate the data and then write all in one go. With the introduction of Netscape Navigator 4, the rendering of JavaScript generated HTML slowed down considerably. The following writes the HTML output to the document in one go:
Select Form FieldsCorrectly navigate select field properties - use the Netscape method. The following technique works in Microsoft Internet Explorer, but should be avoided:
Whereas the following will work correctly in all browsers:
Changing locationDo not use:
The later approach is confusing as it is not clear whether you are changing the location property of the window or the document object, changing the location using the document is deprecated and causes problems on later browsers. Use:
Opening WindowsWhen opening a new popup window using JavaScript there are several points to bare in mind. To be able to control the popup window from the opener window, always retain the returned reference from the window's open method:
To avoid errors when referring to the opener window from the popup window, always check for the in-built browser support for the opener property, and if necessary provide your own:
When updating the contents of a newly opened window, give the browser time to open the window and to load the initial contents:
JavaScript EntitiesJavaScript Entities are only supported by Netscape Navigator - they use should be avoided. The following will cause errors in other browsers:
Instead the following can be used:
JavaScript Source FilesCare must be taken when using JavaScript Source files in Microsoft Internet Explorer 3.0x as using document.write() from within an external source file does not write to the document, and in some instances can cause the browser to crash REF [21]. JavaScript source files an be used in Netscape Navigator 3+ and Microsoft Internet Explorer 3.01+ to hold JavaScript code in an external JavaScript file, that can be embedded in one or many HTML files - the benefit being that once downloaded into the browsers cache it is instantly available for other HTML pages. Before using code within a source file from within the HTML file it is recommended that a test is made to ensure that the source file has actually loaded:
And within library.js:
References and Bibliography
[1] All About JavaScript
[2] ECMA-262, ECMAScript language specification
[3] Netscape JavaScript documentation
[4] Microsoft JScript documentation
[5] irt.org JavaScript documentation
[6] JavaScript the Definitive Guide 3rd Edition by David Flanagan, published by O'Reilly - ISBN 1-56592-392-8
[7] Dynamic HTML The Definitive Reference by Danny Goodman, published by O'Reilly - ISBN 1-56592-494-0
[8] JavaScript the Definitive Guide 2nd Edition by David Flanagan, published by O'Reilly - ISBN 1-56592-234-4
[9] Third party vendor JavaScript tools
[10] Netscape's JavaScript Debugger 1.1
[11] Netscape's Visual JavaScript Trial
[12] The World Wide Web Consortium
[13] ECMAScript and JScript: Two of a Kind
[14] What's New in JavaScript 1.3
[15] JScript - Upgrading Scripting Engines
[16] IT Product Evaluations Process
[17] W3C Working Draft Web Content Accessibility Guidelines
[18] W3C Working Draft Web Content Accessibility Guidelines - Scripts
[19] JavaScript and the ECMA Specification
[20] Microsoft Script Encoder Beta 1 for X86
[21] Internet Explorer 3.02 and SRC files
[22] W3C Recommendation Document Object Model Level 1
[23] W3C Working Draft Document Object Model Level 2
[24] Microsoft Script Debugger 1.0
[25] Microsoft Script Control Download
[26] W3C Recommendation HTML 4.0 Specification
[27] W3C Recommendation HTML 4.0 Strict Document Type Definition
[28] Netscape Client Side JavaScript Reference V1.3, javascript: URL syntax
Feedback on 'JavaScript Guidelines and Best Practice'
View the profile on Martin Webb and the list of other Articles by Martin Webb. |
-- div -->
|