Tips for JS script compatibility

Source: Internet
Author: User
Tags html comment

1. Use HTML to comment out the script

The first question we should consider about compatibility is whether the running platform supports client scripts? Generally, the script body is included in an HTML comment:

<Script language = "javascript">
<! --
Document. write (new Date ());
// -->
</Script>

In this way, browsers that do not support scripts will ignore the <script> and </script> labels and treat other code as an HTML comment. browsers that support scripts will treat "<! -- "This sentence is treated as an HTML comment statement. Other statements are normally executed, and the end of the HTML comment is" --> "use" // "for single line comment.

2. Features and Platform Detection

When the features we want to use are related to the platform, we must first perform detection before using them. There are two ways to detect: one is to directly detect whether the platform supports this feature, the other is to use the corresponding features of the detection platform type. The Code is as follows:

<Script language = "javascript">
<! --
// A. Check whether features are supported
If (s. split ){
A = s. split (","); // supported, used directly
} Else {
A = s. mysplit (","); // not supported. Use the alternative method.
}
// B. Platform Detection
If (navigator. appName. indexOf ("Microsoft ")! =-1 ){
// Use features supported by IE
}
// -->
</Script>

3. Substitution? Ignore? Stop?

If compatibility exists, the solution is to use different features for different platforms or use alternative methods. This is the best practice. But sometimes we cannot solve this problem using the above methods, we can check whether the problem is serious. If the problem is not serious, we can ignore it. For example, a feature does not work on Netscape2, but no one is using Netscape2 now, ignore it. If it cannot be solved but the problem is serious, we should stop running the script and clearly tell the user about the problem!

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.