JavaScript's Emerging API

Source: Internet
Author: User

JavaScript's Emerging API

Category: JavaScript2012-12-31 16:02 215 people read comments (0) favorite reports Many APIs have specific prefixes, such as Microsoft's MS, Google, and Safari's WebKit. These new APIs remove the previous prefix and the rest is the same.  requestanimationframe () is an API for animation repainting, which tells the browser that the animation starts and the browser can determine the best way to redraw. The typical way of early animation is to use the SetInterval () method to control all animations. Here is the basic way of early animation: (function () {   function updateanimations () {      doanimation1 ();   doanimation2 ();  //others  }      setinterval (updateanimations,100 );      }); But on the one hand, in order to make the animation as smooth as possible, you must set the time interval as short as possible, on the other hand due to the browser redraw the number of certain restrictions. To combine these two aspects, the animation should have a cycle interval of 17ms. However, due to setinterval and settimeout performance problems, there will always be a certain delay. To solve this problem, the Mozrequestanimationframe () method is presented, which tells the browser that the JavaScript code needs to be animated. This allows the browser to run some code after the appropriate optimizations. The Mozrequestanimationframe () method receives a parameter, a function that is used before redrawing the screen. This function is responsible for changing the DOM style of the next redraw. function UpdateProgress () {   var Div=document.getelementbyid ("status");   div.style.width= ( parseint (div.style.width,10) +5) + "%";   if (div.style.left!= "100%") {   Mozrequestanimationframe (UpdateProgress);      }}mozrequestanimatioNframe (updateprogress); Calculate how long before the next set of changes on the screen is redrawn: function draw (timestamp) {    var diff=timestamp-starttime;// Count Intervalstarttime=timestamp;mozrequestanimationframe (draw);} var starttime=mozanimationstarttime;mozrequestanimationframe (Draw);  Unlike Mozilla, Webkitrequestanimationframe and Msrequestanimationframe do not first pass a timecode to the callback function, and then Chrome adds a second optional parameter. The DOM element that is about to change. You can refer to the following code for Firefox4+,ie10+,chrome-compatible looping animations: (function () {     function Draw (timestamp) {   var drawstart= (timestamp| | Date.now ()),diff=drawstart-starttime;   starttime=drawstart;   requestAnimationFrame (Draw);  } var requestanimationframe=window.requestaniamtionframe| | window.mozrequeataniamtionframe| |                            Window.webkitrequestanima tionframe| | window.msrequestaniamtionframe,starttime=window.mozanimationstarttime| | Date.now (); Requestaniamtionframe (draw);}) The standard for this API has been drafted, and Mozilla and Googleis participating in the elaboration of the draft standard.  page Visibility API This API is for developers to know whether the page is visible to the user and launched. It consists of three parts: Document.hidden: A Boolean value that indicates whether the page is hidden. Page hiding includes the page in the Background tab or the browser minimized, Document.visibilitystate: Represents the following 4 possible status values: The page in the Background tab or the browser minimized page in the Foreground tab in the actual page has been hidden, However, users can see the preview page of the page performing rendering processing outside the screen. Visibilitychange event: When a document is changed from visible to invisible or never visible, only IE10 and Chrome support this API. The front prefix of IE is prefixed with ms,chrome prefix webkit. The best way to check if the browser supports this API: function ishidddensupported () {   return typeof (Document.hidden| | document.mshidden| | Document.webkithidden)! = "undefined";} Check if the page is hidden: if (document.hidden| | document.mshidden| | Document.webkithidden) {//hidden}else{//} now only the Document.hidden property is generic, and this part of the API is relatively stable, so it can be used in real development. The  geolocation API geo-location API,JAVASCRIPT code can access the user's current location through it. Of course, the user's explicit permission to do so. The implementation of this API in the browser is the Navigator.geolocation object, which contains three methods. The first method is GetCurrentPosition (), which invokes this method to trigger a dialog box that asks the user to share geolocation information. This method receives three parameters: a successful callback function, an optional failure callback function, and an optional option object. Where the success callback function accepts a position object parameter, which has two properties: Coords and timestamp. The Coords object will contain the following location-related information. Latitude: Latitude Longitude in decimal degrees: the degree accuracy in decimal degrees: the precision of latitude coordinates, in meters the browser may also provide the following in the Coords objectProperty. Altitude: In meters of altitude, no relevant data for nullaltitudeaccuracy: altitude accuracy, the larger the more inaccurate heading: The direction of the compass, 0 degrees north, the value of Nan means that no data is detected speed: velocity, Unit meters per second, or null if there are no related data. In real-world development, latitude and longitude are the most commonly used properties for most wen applications. For example, the following code will draw the user's location on the map: navigator.geolocation.getCurrentPosition (function (position) {  drawmapcenteredat ( postion.coords.latitude,position.coords.longitude);}); The second parameter of the GetCurrentPosition () method, the failed callback function, receives a parameter when it is called. This parameter contains two properties of message and code. Where the message property holds the text message to the person explaining why the error occurred. The code holds a value that indicates the type of error: User denied sharing (1), invalid location (2), timeout (3). In actual development, most Web applications will only save error messages to the log. The third parameter of the GetCurrentPosition () method is an optional object that sets the type of information. Navigator.geolocation.getCurrentPosition (function (position) {  drawmapcenteredat ( Postion.coords.latitude,position.coords.longitude);},function (Error) {console.log ("Error code:" +error.code); Console.log ("Error message:" +error.message);},{enablehighaccuracy:true,//means using the most accurate location information possible timeout:5000,// The maximum time to wait for location information in milliseconds maximumage:25000//represents the effective time of the last coordinate information obtained, in milliseconds, and if time is up, the new coordinate information is re-acquired. }); If you want to track the user's location, you can use Watchposition (). This method accepts parameters with GETC.The urrentposition () effect is exactly the same. Calling this method returns a numeric identifier that is used to track the monitoring operation. Based on this return value, the monitoring operation can be canceled. var watchid=navigator.geolocation.watchposition (function (position) {Drawmapcenteredat (Position.coords.latitude, Position.coords.longitude);  },function (Error) {console.log ("Error code:" +error.code); Console.log ("error message:" +error.message);}); Clearwatch (Watchid); the  file Apifilereader type implements an asynchronous file-reading mechanism. You can think of FileReader as XMLHttpRequest, except that it reads a file system, not a remote server. To read the data in the file, FileReader provides several methods: Readastext (file,encoding): reads the file as a plain file and saves the read file to the result property. The second parameter is used to specify the encoding type, optional. Readasdataurl (file): reads the file and saves the file as a data URI in the Result property readasbinarystring (file): reads the file and saves a string in the result property, Each character of the string represents a byte Readasarraybuffer (file): reads the file and saves a arraybuffer containing the contents of the file in the result property because the process of reading the file is asynchronous, so FileReader provides several events. The most commonly used events are three: Progress,load,error indicates whether new data has been read again, whether the entire file has been read, and whether an error has occurred. The progress event is triggered every 50ms, and the contents of the file are read through the event's properties that can get the event: the Lengthcomputable,loaded and Total.result properties. Here is an example of using three events: Var Filelist=document.getelementbyid ("Files-list"); Eventutil.addhandler (fileslist, "Change", FunctiOn (event) {           var info= "", Output=document.getelementbyid ("Output"),   Progress=document.getelementbyid ("Progress"),   Files=eventutil.gettarget (event) .files,   Type= "Default", Reader=new FileReader ();      if (/image/.test (files[0].type)) {    Reader.readasdataurl (files[0]);   type= "image";  }else{   reader.readAsText ( Files[0]);   type= "text";  }      reader.onerror=function () {    Output.innerhtml= "Could not read file, error code is" +               &NBSP ;     reader.error.code;   };      reader.onprogress=function ( Event) {   if (event.lengthcomputable) {   progress.innerhtml=event.loaded+ "/" +event.total;     }    };      Reader.onload=fuNction () {   var html= "";   switch (type) {      case "image": html= "
  • An explanation of the advanced JavaScript techniques
  • Next SVG Introduction
Topic recommendation
javascriptweb Application developer File System geolocation
Guess you're looking for
JavaScript System Folder file operation (very powerful OH)
JavaScript-based compression and decompression and file system demo
IE8 "Developer Tools" in detail (browser mode, text mode, JavaScript debugging, Profiler)
IE8 "Developer Tools" in detail (browser mode, text mode, JavaScript debugging, Profiler)
2013 JavaScript Developer survey results
debugging JavaScript errors using the F12 developer Tools
Web Developer's favorite 10 popular JavaScript libraries
IE8 "Developer Tools" in detail (browser mode, text mode, JavaScript debugging, Profiler)
21 Tips for JavaScript developers (i)
the future of the Javascript:web application of the same shape
View Comments
No Comments

* The above user statements represent only their personal views, do not represent the views or positions of the CSDN site core technology category all topics Hadoop AWS mobile games Java Android IOS Swift Smart hardware Docker OpenStack VPN Spark ERP IE1 0Eclipse CRM JavaScript Database Ubuntu NFC WAP jQuery BI HTML5 Spring Apache. NET API HTML SDK iisfedora XML LBS Unity Splasht OP UML components Windows Mobile Rails QEMU KDE Cassandra CloudStack ftccoremail OPhone couchbase cloud computing iOS6 Rackspace Web A PP Springside Maemo Compuware big Data aptech perltornado Ruby Hibernate thinkphp HBase Pure Solr Angular Cloud Foundry Redis S Cala Django Bootstrap
      Personal Information

God gave me money.
      • Visit: 31,483 times
      • Points: 1135 minutes
      • Rank: 14,415th Place
      • Original: 83 Articles
      • Reprinted: 16 Articles
      • Translation: 3 articles
      • Comments: 3
      Article Search
      article Categories
    • Java (28)
    • JavaScript (35)
    • SQL (3)
    • SVG (3)
    • STRUCTS2 (4)
    • Reading notes (37)
    • My Programmer's Way (7)
    • UML Basics (12)
      Article archive
    • September 2014 (2)
    • June 2014 (1)
    • May 2014 (2)
    • January 2014 (3)
    • November 2013 (1)
Expand
      Read the rankings
    • Introduction to various views of UML (2299)
    • Code for a Java state Machine sample (2107)
    • Structs2 Working principle (1985)
    • SVG Animation Animation (1829)
    • JavaScript Dom detailed DOM2 and DOM3 (957)
    • Java Arrays.sort usage issues (587)
    • JavaScript scripted HTTP----The cornerstone of Ajax (561)
    • JavaScript svg animations, scripts, events (544)
    • SPRINGMVC Rapid Breakthrough (iii)---One controller multiple method problems (530)
    • JavaScript json detailed (476)
      Comment Ranking
    • Introduction to various views of UML (2)
    • JavaScript dom Extensions (1)
    • Java printing Triangles, diamond methods (0)
    • I hang after the idea (0)
    • Personal analysis of proxy mode (0)
    • Sick, sitting in front of the computer in a daze when cranky (0)
    • SVG Animation Animation (0)
    • Java Collections (0)
    • Java database Programming (0)
    • UML Fundamentals and Necessity (0)
      Featured Articles
      Latest Comments
    • Introduction to various views of UML

      God gave me money: Be sure that it contains what you want before you look, and that urgency is inversely proportional to the degree of boredom.

    • Introduction to various views of UML

      Changshenglugu: Don't Look in ...

    • JavaScript DOM Extensions

      God gave me the money: element traversal problem elements traversal specification in order to resolve some browser compatibility issues, element Tr ...

Company Profile | careers | Advertising SERVICES | Bank Transfer account | contact | copyright | Legal Counsel | PROBLEM Report | partners | Forum Feedback
website Customer Service magazine customer Service Micro Blog service [email protected] 400-600-2320
Beijing ICP Certificate No. No. 070598
Beijing Innovation Music Information Technology Co., ltd All rights reserved
Jiangsu le know Network Technology Co., Ltd. to provide business support
copyright©1999-2014, csdn.net, All rights Reserved

JavaScript's Emerging API

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.