IBM official information migrates applications from Internet Explorer to Mozilla 1th/2 page _javascript tips

Source: Internet
Author: User
Tags call back html tags object model processing instruction reserved
--> --> -->

When Netscape first developed Mozilla browsers, it wisely decided to support the standards of the consortium. As a result, Mozilla and Netscape Navigator 4.x and Microsoft Internet Explorer legacy code are not fully backward compatible, as will be mentioned later in the Mozilla support <layer> . Internet Explorer 4 These browsers that were built before the concept of the Web-Consortium standard have inherited a lot of quirks. This article discusses the special pattern of Mozilla, which provides powerful HTML backward compatibility features for Internet Explorer and other legacy browsers.

I will also discuss non-standard technologies supported by Mozilla, such as XMLHttpRequest and rich-text editors, since there is no corresponding standard for the consortium. These include:

  • HTML 4.01 and XHTML 1.0/1.1
  • Cascading style Sheets (CSS): TheCSS Level 1,CSS Level 2 , and part of the CSS levels 3 .
  • Document Object Model (DOM): part ofDOM Level 1, DOM Level 2 , and DOM level 3
  • Mathematical Markup Language:MathML Version 2.0
  • Extensible Markup Language (XML):XML 1.0,Namespaces in XML,associating Style Sheets with XML Documents 1.0, Fragment Identifier for XML
  • XSL Transformations:XSLT 1.0
  • XML Path Language:XPath 1.0
  • Resource Description Framework:RDF
  • Simple Object Access Protocol:SOAP 1.1
  • ECMA-262 Revision 3 (JavaScript 1.5):ECMA

Common cross-browser coding techniques

Although WEB standards exist, the behavior of different browsers is not exactly the same (in fact, the same browser behaves differently on different platforms). Many browsers, such as Internet Explorer, still support APIs that have not been widely supported in the Web-compatible browsers before the consortium.

Before delving into the differences between Mozilla and Internet Explorer, let's start with some basic ways to make your WEB application scalable so that you can add new browser support later.

Because different browsers sometimes use different APIs for the same functionality, they often see a lot of blocks in the code if() else() to differentiate between different browsers. The following code block is used for Internet Explorer:

 
. . . 

var Elm; 

if (NS4) 
 elm = document.layers["MyID"]; 
else if (ie4) 
 elm = document.all["MyID"]; 

The above code is not extensible, and if you need to support a new browser, you must modify all such blocks of code in your WEB application.

The easiest way to avoid recoding new browsers is to abstract functionality. Instead of using layers of nested if() else() blocks, abstracting common tasks into separate functions can improve efficiency. This not only makes the code easier to read, it also makes it easier to add new client support:

 
var elm = Getelmbyid ("MyID"); 

function Getelmbyid (AID) { 
 var element = null; 

 if (Ismozilla | | isIE5) 
 ? element = document.getElementById (AID) 
 else if (isNetscape4) 
 element = Document.layers[aid] 
 else if (isIE4) 
 element = Document.all[aid]; 

 return element; 
} 

The above code still has problems with the browser sniffing or detecting which browsers the user is using. Browser sniffing is typically done through user agents, such as:

 
 mozilla/5.0 (X11; U Linux i686; En-us; rv:1.5) gecko/20031016 

Although using the user agent to sniff the browser provides the details of the browser you are using, the code that handles the user agent may be wrong when a new browser version occurs, and you need to modify the code.

If the type of browser does not matter (assuming that the WEB application is forbidden to be accessed by browsers), it is best to sniff through the capabilities of the browser itself. You can usually do this by testing the JavaScript functionality you need. For example, instead of using:

 
 if (Ismozilla | | isIE5) 

Why not use:

 
 if (document.getElementById) 

Without any modification, you can work in other browsers that support the method, such as Opera or Safari.

But if accuracy is important, such as verifying that the browser meets the version requirements of the WEB application or trying to avoid a bug, you must use the user agent sniffer.

JavaScript also allows you to use inline conditional statements to help improve the readability of your code:

 
 var foo = (condition)? Conditionistrue:conditionisfalse; 

For example, to retrieve an element, you can use the following code:

 
function GetElement (aid) {return 
 (document.getElementById)? document.getElementById (Aid)
          : document.all[ AID];
} 





Back to the top of the page


The difference between Mozilla and Internet Explorer

First, discuss the differences between Mozilla and Internet Explorer in the way HTML behaves.

Tool Tips

Legacy browsers introduce tooltips in HTML, displaying alt properties as the content of ToolTips on links. The latest HTML specification for the new version of the consortium adds title attributes that are used to include detailed descriptions of links. Modern browsers should use title properties to display ToolTips, and Mozilla only supports displaying ToolTips with this property instead of alt attributes.

Entity

HTML tags can contain multiple entities, which are specifically defined by theW3 standard body . You can refer to these entities by numeric or character references. For example, you can use a #160 or equivalent character reference   to reference whitespace characters   .

Some of the older browsers, such as Internet Explorer, have some weird places, such as allowing the semicolon to be replaced with normal text content ( ; ):

 
 Foo 
 foo 

Mozilla will present the above   as a space, although violating the rules of the consortium. If you follow more characters, the browser cannot parse it   , such as:

 
 &nbsp12345 

Such code is not valid in Mozilla because it violates the W3 standard. To avoid browser differences, stick with the correct form (   ).





Back to the top of the page


DOM differences

A Document Object Model (DOM) is a tree structure that contains document elements. You can manipulate it through the JavaScript API, which is already standard for this consortium. But before the standardization of the Consortium, Netscape 4 and Internet Explorer 4 implemented the API in a similar fashion. Mozilla only implements those legacy APIs that are not supported by the standards of the consortium.

accessing elements

References to elements that are not retrieved in a cross-browser manner should be used document.getElementById(aID) , which can be used for Internet Explorer 5.5+, Mozilla, and is part of the DOM Level 1 specification.

Mozilla does not support document.elementName accessing elements by even the element name, while Internet Explorer supports this approach (also known as global namespace pollution ). Mozilla also does not support Netscape 4 's document.layers approach and Internet Explorer's document.all approach. In addition to document.getElementById retrieving elements, you can also use document.layers and get a list of all document.all the document elements that have a specific label name, such as all <div> elements.

The consortium DOM Level 1 uses getElementsByTagName() methods to get references to elements of all the same label names. This method returns an array in JavaScript, can be used for document elements, and is available for other nodes to retrieve only the corresponding subtree. To get a list of all the elements in the DOM tree, use the getElementsByTagName(*) .

The DOM Level 1 method is listed in table 1, most used to move elements to specific locations or to toggle their visibility (menus, animations). Netscape 4 uses <layer> the label (Mozilla does not support) as an HTML element that can be positioned arbitrarily. In Mozilla, you can use <div> tags to locate elements, and Internet Explorer uses them, as well as the HTML specification.

table 1. Methods for accessing elements

Method Description
document.getElementById (AID) Returns a reference to the element with the specified ID.
document.getElementsByTagName (Atagname) Returns an array of elements with the specified name in the document.

Traverse DOM

Mozilla uses JavaScript to support the the DOM API for traversing the tree, as shown in table 2. These API methods can be used by each node in the document to traverse the tree in any direction. Internet Explorer also supports these APIs, as well as the APIs originally used to traverse the DOM tree, such as children attributes.

table 2. Methods for traversing the DOM

The
Properties/Methods Description
ChildNodes Returns an array of all child nodes of an element.
FirstChild Returns the first child node of an element.
GetAttribute (Aattributename) Returns the value of the specified property.
Hasattribute (Aattributename) Returns a Boolean value indicating whether the current node contains a property of the specified name.
HasChildNodes () Returns a Boolean indicating whether the current node has child nodes.
LastChild Returns the last child node of an element.
NextSibling Returns the node immediately following the current node.
NodeName Returns the name of the current node with a string.
nodeType Returns the type of the current node.

value description
1 element node
2 Property node
3 text node
4 CDATA Select node
5 entity reference node
6 entity node
7 processing instruction node
8 Comment node
9 document node
Ten Document type node
one document fragment node
symbol node

NodeValue Returns the value of the current node. Returns its string value for nodes that contain text, such as text and comment nodes. Returns the property value for the property node. The other node returns null .
Ownerdocument Returns the object that contains the current node document .
ParentNode Returns the parent node of the current node.
PreviousSibling Returns the adjacent node before the current node.
RemoveAttribute (Aname) Deletes the specified property from the current node.
SetAttribute (Aname, Avalue) Sets the value of the specified property.

Internet Explorer has a non-standard special behavior that many of these APIs skip (for example) a blank text node generated by new line characters. Mozilla does not skip, so it is sometimes necessary to differentiate between these nodes. Each node has a nodeType property that specifies the node type. For example, the element node type is 1, the text node is 3, and the annotation node is 8. The best way to deal with element nodes is to iterate through all the child nodes and then process the nodes that are NodeType 1:

 
 HTML: 
 <div id= "foo" > 
  <span>Test</span> 
 C </div> 

 JavaScript: 
 var mydiv = document.getElementById ("foo"); 
 var mychildren = myxmldoc.childnodes; 
 for (var i = 0; i < mychildren.length i++) { 
  if (Mychildren[i].nodetype = 1) { 
  //element node
  }
 }

Generate and manipulate content

Mozilla supports legacy methods for dynamically adding content to the DOM, such as document.write , document.open and document.close . Mozilla also supports the Internet Explorer InnerHTML approach, which can be used on virtually any node. However, it is not supported OuterHTML (tagging around elements, there is no equivalent method in the standard) and innerText (setting the text value of a node to be used in Mozilla textContent ).

Internet Explorer has some non-standard, Mozilla unsupported content manipulation methods, including retrieving values, inserting text, and inserting elements adjacent to a node, such as getAdjacentElement and insertAdjacentHTML . Table 3 illustrates the standards of the consortium and the ways in which Mozilla manipulates content, and these methods apply to any DOM node.

Table 3. Mozilla's approach to manipulating content

Method Description
AppendChild (Anode) Creates a new child node. Returns a reference to the new child node.
CloneNode (Adeep) Creates a copy of the call node and returns. If Adeep is true, the entire subtree of the node is replicated.
CreateElement (Atagname) Creates and returns a Atagname-free DOM node of the specified type.
createTextNode (Atextvalue) Creates and returns a new, parent-free DOM text node, which is specified by Atextvalue.
InsertBefore (Anewnode, Achildnode) Insert Anewnode before Achildnode, which must be a child node of the current node.
RemoveChild (Achildnode) Deletes the Achildnode and returns a reference to it.
ReplaceChild (Anewnode, Achildnode) Replaces Achildnode with Anewnode and returns a reference to the deleted node.

Document fragment

For performance reasons, you can create a document in memory instead of working with the DOM of an existing document. The DOM Level 1 Core introduces a document fragment, a lightweight document that contains a subset of the generic document interface. Like no getElementById , but there's appendChild . It is easy to add a document fragment to an existing document.

Mozilla uses the document.createDocumentFragment() create document fragment, which returns an empty document fragment.

However, the implementation of the document fragment of Internet Explorer does not conform to the universal standard, only returns the general document.





Back to the top of the page


JavaScript differences

Most of the differences between Mozilla and Internet Explorer are related to JavaScript. But the problem usually comes from APIs that the browser exposes to JavaScript, such as DOM hooks. The two browsers are not very different in core JavaScript, and the problems encountered are usually related to time.

JavaScript Date Differences

DateThe only difference is the getYear method. According to the ECMASCRIPT specification (which is the specification followed by JavaScript), this method does not solve the millennium problem, and running in 2004 new Date().getYear() will return "104". According to the ECMASCRIPT specification, the getYear returned year minus 1900 was originally intended to return "98" in 1998. ECMAScript Version 3 was abolished getYear , with the getFullYear() substitution. Internet Explorer has modified getYear() it and getFullYear() similar to eliminate the millennium problem, while Mozilla insists on adopting a standard behavior approach.

JavaScript Execution Differences

Different browsers perform JavaScript in different ways. For example, the following code assumes that script the div node already exists in the DOM when the block executes:

 
... 
<div id= "foo" >Loading...</div> 

<script> 
 document.getElementById ("foo"). InnerHTML = " Done. "; 
</script> 

But that is not guaranteed. To ensure that all elements already exist, you should <body> use onload an event handler for the element:

 
<body onload= "Dofinish ()" > 

<div id= "foo" >Loading...</div> 

<script> 
 function Dofinish () { 
 var element = document.getElementById ("foo");
	 element.innerhtml = "done."; 
 } 
</script> ... 
 

This kind of time-related problems are also related to hardware, and slower systems may find bugs that are hidden by fast systems. A concrete example is window.open that it opens a new window:

 
<script> 
 function Doopenwindow () { 
var Mywindow = window.open ("About:blank"); 
MyWindow.location.href = "http://www.ibm.com"; 
 } 
</script> 

The problem with this code is that it window.open is asynchronous and does not block JavaScript execution until the window is opened. As a result, window.open subsequent rows may be executed before a new window is opened. You can resolve this problem in a handler for a new window onload , and then call back to open its window (use window.opener ).

JavaScript generates HTML differences

JavaScript can document.write generate HTML by instantly using strings. The main problem is what to do if JavaScript generated HTML that is embedded in an HTML document (and therefore also in a <script> label) contains <script> tags. If the document is in strict rendering mode , it will interpret the string as the </script> <script> end tag of the outer layer. The following code is a good illustration of this:

 
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" 
 "http://www.w3.org/TR/xhtml1/DTD/ Xhtml1-transitional.dtd "> ... 
<script> 
 document.write ("<script>alert (" Hello ") </script>") 
</script> 

Because the page is in strict mode, the Mozilla parser will see the first <script> and parse it until it finds the first ending tag, the first </script> . This is because the parser does not know when JavaScript (or any other language) uses strict mode. In special mode, the parser parses JavaScript (and thus slows it down) during parsing. Internet Explorer always takes a special mode, so it does not really support XHTML. In order to use strict mode in Mozilla, you need to break the string into two parts:

 
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" 
 "http://www.w3.org/TR/xhtml1/DTD/ Xhtml1-transitional.dtd "> ... 
<script> 
 document.write ("<script>alert (" Hello ") </" + "script>") 
</script> 

Debugging JavaScript

Mozilla provides a variety of ways to debug JavaScript-related issues in applications created for Internet Explorer. The first tool is the built-in JavaScript console, as shown in Figure 1, which records error and warning messages. Choose Tools -> Web Development-> JavaScript Consolein Mozilla, or select tools in Firefox (a standalone browser product from Mozilla) -> JavaScript Console to open it.


Figure 1. JavaScript Console

The JavaScript console can display a complete list of logs, or you can display errors, warnings, and messages, respectively. The error message in Figure 1 indicates that the variable is_ns70 accessed on line 95th of aol.com does not exist. Click the link to open the View source window inside Mozilla, highlighting the line that went wrong.

The console also allows for JavaScript evaluation. To calculate the JavaScript syntax for the input, enter it in the input field 1+1 and press Evaluate, as shown in Figure 2.


Figure 2. JavaScript Console Evaluation

Mozilla's JavaScript engine builds support for debugging, providing a powerful tool for JavaScript developers. The venkman shown in Figure 3 is a powerful cross-platform JavaScript debugger that integrates with Mozilla. It is usually bundled with the Mozilla release pack and can be opened by selecting the Tools-> Web Development-> JavaScript Debugger . Firefox is not bundled with this debugger, but can download the installation from http://www.mozilla.org/projects/venkman/ . You can also find tutorials on the development page, and the URL for the development page is http://www.hacksrus.com/~ginda/venkman/.


Figure 3. Mozilla JavaScript Debugger

The JavaScript debugger can debug JavaScript that runs in the Mozilla browser window. It supports standard debugging features such as breakpoint management, viewing call stacks, and variable/object checking. All features can be accessed through the user interface or the debugger's interactive console. With the console, you can execute any JavaScript within the same scope as the JavaScript code that you are debugging.

Current 1/2 page 12 Next read the full text
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.