Official IBM documents migrate applications from Internet Explorer to Mozilla page 1/2

Source: Internet
Author: User

When Netscape first developed the Mozilla browser, it was wise to decide to support W3C standards. Therefore, Mozilla, Netscape Navigator 4.x, and Microsoft Internet ExplorerCodeNot fully backward compatible. For example, Mozilla does not support<Layer>. Internet Explorer 4 These browsers created before the emergence of W3C standards inherit a lot of weirdness. This article will discuss Mozilla's special mode, which provides powerful HTML backward compatibility functions for Internet Explorer and other legacy browsers.

I will also discuss non-standard technologies supported by Mozilla, such as XMLHttpRequest and rich text editing, because W3C had no corresponding standards at the time. Including:

    • HTML 4.01 and XHTML 1.0/1.1
    • Cascading Style Sheets (CSS): CSS Level 1, CSS Level 2, and CSS Level 3.
    • Document Object Model (DOM): Dom Level 1, Dom Level 2, and Dom level 3
    • Math 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 conversion: XSLT 1.0
    • XML Path: XML 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 skills

Although there are web standards, the behavior of different browsers is not exactly the same (in fact, the behavior of the same browser on different platforms is also different ). Many browsers, such as Internet Explorer, still support APIs earlier than W3C that have never been widely supported in W3C compliant browsers.

Before going into the differences between Mozilla and Internet Explorer, let's first introduce how to make Web ApplicationsProgramSome basic methods of scalability to support new browsers in the future.

Because different browsers sometimes use different APIs for the same function, we often see a lotIf () else ()Block to treat different browsers differently. 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 scalable. To support new browsers, you must modify all such code blocks in Web applications.

The simplest way to avoid re-encoding for a new browser is to abstract the function. Do not use layer-by-layer nestingIf () else ()And abstract general tasks into separate functions to improve efficiency. This not only makes the code easier to read, but also facilitates the support of new clients:

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 existsBrowser sniffingOr you can check the browser you are using. Browser sniffing is generally completed through a user agent, for example:

Mozilla/5.0 (X11; U; Linux i686; en-US; RV: 1.5) Gecko/20031016

Although the user agent is used to sniff the detailed information of the browser used, the code for processing the user agent may fail when a new browser version appears, so you need to modify the code.

If the browser type is irrelevant (assuming that unsupported browsers are prohibited from accessing Web applications), it is best to sniff through the browser's own capabilities. Generally, you can test the required JavaScript function. For example, instead of using:

If (ismozilla | isie5)

Better use:

If (document. getelementbyid)

In this way, other browsers that support this method, such as opera or Safari, can work without any modification.

However, if the accuracy is very important, such as verifying whether the browser meets the web application version requirements or trying to avoid a bug, you must use the user agent to sniff.

Javascript also allows the use of nested condition statements to improve code readability:

VaR Foo = (condition )? Conditionistrue: conditionisfalse;

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

Function getelement (AID) {return (document. getelementbyid )? Document. getelementbyid (AID): Document. All [aid];}


Back to Top

Differences between Mozilla and Internet Explorer

First, we will discuss the differences between Mozilla and Internet Explorer in HTML behavior.

Tooltip

The legacy browser introduces a tooltip in HTML, which is displayed on the link.ALTAttribute as the content of the tooltip. The latest W3C HTML specification has been addedTitleAttribute, used to include detailed descriptions of links. Modern browsers should useTitleProperty display tooltip. Mozilla only supports this property display tooltip, but notALTAttribute.

Entity

HTML tags can contain multiple types of entities. W3 standard bodies are specifically defined. These entities can be referenced by numbers or character references. For example, you can use #160 or equivalent characters to reference To reference white space characters .

Some old browsers, such as Internet Explorer, have some strange things, such as allowing replacement of semicolons (;):

& Nbsp Foo & nbsp foo

Mozilla will& NbspRendered as a space, which violates W3C specifications. If more characters are followed, the browser cannot parse& NbspSuch:

& Nbsp12345

This code is invalid in Mozilla because it violates the W3 standard. In order to avoid the difference between browsers, we should stick to the correct form ( ).



Back to Top

Dom difference

The Document Object Model (DOM) is a tree structure containing document elements. You can use JavaScript APIs to manipulate it, which is a W3C standard. However, before W3C standardization, Netscape 4 and Internet Explorer 4 implemented this API in a similar way. Mozilla only implements those legacy APIs not supported by W3C standards.

Access Element

Reference of elements not retrieved in cross-browser mode should be usedDocument. getelementbyid (AID)This method can be used in Internet Explorer 5.5 + and Mozilla, and is part of the DOM Level 1 specification.

Mozilla does not supportDocument. elementnameYou can even access an element by element name. Internet Explorer supports this method (also knownGlobal namespace pollution). Mozilla does not support Netscape 4 either.Document. LayersMethod and Internet ExplorerDocument. AllMethod. BesidesDocument. getelementbyidYou can also search for elements.Document. LayersAndDocument. AllObtain a list Of all document elements with a specific tag name, such as all<Div>Element.

W3C Dom Level 1 usageGetelementsbytagname ()Method To obtain references to all elements with the same tag name. This method returns an array in JavaScript and can be usedDocumentIt can also be used by other nodes to retrieve only the corresponding subtree. To obtain a list of all elements in the DOM tree, you can useGetelementsbytagname (*).

Table 1 lists the DOM Level 1 methods, most of which are used to move elements to a specific location or switch their visibility (menus, animations ). Use Netscape 4<Layer>Tags (not supported by Mozilla) are HTML elements that can be located at will. In Mozilla<Div>Tag positioning element, which is also used by Internet Explorer and also included in the HTML specification.

Table 1. Methods used to access elements

Method Description
Document. getelementbyid (AID) Returns a reference to an 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 W3C Dom APIs that traverse the DOM tree (as shown in table 2 ). Each node in this document can use these API methods to traverse the tree in any direction. Internet Explorer also supports these APIs and APIs used to traverse the DOM tree, suchChildrenAttribute.

Table 2. Methods used to traverse the DOM

Attribute/Method Description
Childnodes Returns an array of all child nodes of an element.
Firstchild Returns the first subnode of an element.
Getattribute (aattributename) Returns the value of the specified property.
Hasattribute (aattributename) Returns a Boolean value indicating whether the current node contains the attribute of the specified name.
Haschildnodes () Returns a Boolean indicating whether the current node has a subnode.
Lastchild Returns the last subnode of an element.
Nextsibling Returns the node that follows the current node.
Nodename Returns the name of the current node using a string.
Nodetype Returns the type of the current node.

Value Description
1 Element Node
2 Attribute node
3 Text Node
4 CDATA Node Selection
5 Entity reference node
6 Entity Node
7 Processing Command Node
8 Comment nodes
9 Document Node
10 Document Type Node
11 Document segment Node
12 Symbol Node
Nodevalue Returns the value of the current node. Return the string value of a node that contains text, such as text and comment. Attribute values are returned for Attribute nodes. Other node returnNull.
Ownerdocument ReturnsDocumentObject.
Parentnode Returns the parent node of the current node.
Previussibling Returns the adjacent node before the current node.
Removeattribute (aname) Deletes a specified attribute from the current node.
Setattribute (aname, avalue) Set the value of the specified attribute.

Internet Explorer has a non-standard special behavior. Many of these Apis SKIP (for example,) blank text nodes generated by new line characters. Mozilla does not skip, So you sometimes need to differentiate these nodes. Each node hasNodetypeThe Property specifies the node type. For example, the element node type is 1, the text node is 3, and the comment node is 8. The best way to process only element nodes is to traverse all child nodes and then process those nodes whose nodetype is 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 the legacy Method for dynamically adding content to Dom, as shown in figureDocument. Write,Document. OpenAndDocument. Close. Mozilla also supportsInnerhtmlMethod, which can be basically used on any node. But not supportedOuterhtml(Adding a tag around the element does not have an equivalent method in the standard) andInnertext(Set the node text value, which can be used in MozillaTextcontent).

Internet Explorer has some non-standard content operation methods not supported by Mozilla, including retrieving values, inserting text, and inserting elements near a node, suchGetadjacentelementAndInsertadjacenthtml. Table 3 describes W3C standards and how Mozilla operates content. These methods apply to any dom node.

Table 3. Mozilla content manipulation

Method Description
Appendchild (Anode) Create a new subnode. Returns the reference of the new subnode.
Clonenode (adeep) Create a copy of the call node and return it. If adeep is true, the entire subtree of the node is copied.
Createelement (atagname) Create and return a parent-less Dom node of the specified type of atagname.
Createtextnode (atextvalue) Create and return a new non-parent Dom text node. The value is specified by atextvalue.
Insertbefore (anewnode, achildnode) Insert anewnode before achildnode. The former must be a subnode of the current node.
Removechild (achildnode) Delete achildnode and return a reference to it.
ReplaceChild (anewnode, achildnode) Replace achildnode with anewnode and return the reference of the deleted node.

Document snippets

For performance reasons, you can create a document in memory instead of processing the DOM of an existing document. Dom Level 1 core introduces document snippets, a subset of a lightweight document that contains common document interfaces. For example, noGetelementbyidHoweverAppendchild. It is easy to add document fragments to existing documents.

Use MozillaDocument. createdocumentfragment ()Create a document clip. This method returns an empty document clip.

However, the implementation of document fragments in Internet Explorer does not follow W3C standards, and only common documents are returned.



Back to Top

Javascript differences

Most of the differences between Mozilla and Internet Explorer are related to JavaScript. However, the problem is usually caused by APIs exposed by browsers to Javascript, such as Dom hooks. The two browsers have little difference in the core JavaScript, and the problem is usually related to time.

Javascript date difference

DateThe only difference is thatGetyearMethod. According to the ecmascript specification (this is the specification followed by JavaScript), this method did not solve the millennium problem and was run in 2004.New Date (). getyear ()104 is returned ". According to ecmascript specifications,GetyearThe returned year minus 1900 is initially returned for "98" on January 1, 1998 ". Ecmascript Version 3 abolishedGetyear, UseGetfullyear (). Internet Explorer modifiedGetyear ()Make it andGetfullyear ()Similarly, the millennium issue was eliminated, while Mozilla insisted on adopting standard behavior patterns.

Differences in JavaScript Execution

Different browsers execute Javascript in different ways. For example, the following code assumesScriptWhen the block is executedDivThe node already exists in the DOM:

... <Div id = "foo"> loading... </div> <SCRIPT> document. getelementbyid ("foo "). innerhtml = "done. "; </SCRIPT>

However, this cannot be guaranteed. To ensure that all elements already exist<Body>Element usageOnloadEvent Handler:

<Body onload = "dofinish ()"> <Div id = "foo"> loading... </div> <SCRIPT> function dofinish () {var element = document. getelementbyid ("foo"); element. innerhtml = "done. ";}</SCRIPT>...

These time-related problems are also related to hardware. Slow systems may find Bugs hidden by fast systems. A specific example is:Window. Open, Which 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 thatWindow. OpenIt is asynchronous. Javascript execution is not blocked before the window is opened. Therefore,Window. OpenThe following rows may be executed before the new window is opened. You canOnloadSolve the problem in the handler, and then open its window through the callback (UseWindow. Opener).

Differences between JavaScript-based HTML generation

Javascript can useDocument. WriteGenerate HTML with strings in real time. The main problem is that if embedded in an HTML document (<SCRIPT>The HTML generated by JavaScript contains<SCRIPT>Label. If the document adopts the strict rendering mode</SCRIPT>Interpreted as outer layer<SCRIPT>. The following code demonstrates this well:

<! 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 adopts the strict mode, the Mozilla parser will see the first<SCRIPT>And parse it until the first end tag is found, that is, the first end tag.</SCRIPT>. This is because the parser does not know when JavaScript (or any other language) uses the strict mode. In special mode, the parser analyzes JavaScript During the parsing process (thus reducing the speed ). Internet Explorer always adopts special mode, so it does not really support XHTML. To use the strict mode in Mozilla, You need to split 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>

Debug Javascript

Mozilla provides multiple methods to debug JavaScript-related issues in Applications created for Internet Explorer. The first tool is the built-in JavaScript console, as shown in 1, which records error and warning information. SelectTools-> Web development-> JavaScript ConsoleOr selectTools-> JavaScript ConsoleYou can open it.

Figure 1. Javascript Console

The javascript console displays the complete log list, errors, warnings, and messages. The error message in Figure 1 indicates that the variable is_ns70 accessed by row aol.com 95th does not exist. Click this link to open the Mozilla internal viewSource codeWindow to highlight the wrong line.

The console also allows you to evaluate JavaScript. To calculate the input JavaScript syntax, enter it in the input field1 + 1Then pressEvaluate, As shown in result 2.

Figure 2. Evaluate the Javascript Console

Mozilla's JavaScript engine has built-in debugging support, which provides JavaScript developers with powerful tools. As shown in figure 3, Venkman is a powerful cross-platform JavaScript debugger that is integrated with Mozilla. It is usually bundled with the Mozilla release package. You can selectTools-> Web development-> JavaScript DebuggerOpen it. Firefox does not bind this debugger, but you can download the installation from the http://www.mozilla.org/projects/venkman. You can also find the relevant tutorials on the Development page, the Development page url is http://www.hacksrus.com /~ Ginda/Venkman /.

Figure 3. Mozilla JavaScript Debugger

The javascript debugger can debug JavaScript running in the Mozilla browser window. It supports standard debugging features such as breakpoint management, viewing call stacks, and checking variables/objects. All features can be accessed through the user interface or the interactive console of the debugger. Through the console, You can execute any JavaScript code in the same scope as the JavaScript code for debugging.

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.