Computer Coding
Home |  ColdFusion |  IBM |  Java |  JavaScript |  Spring |  Misc |  Sign in



HTML5Rocks


dialog element: shipped in Chrome 37 Beta

Chrome Beta has landed its native support for <dialog> element without needing "Enable experimental Web Platform features." flag turned on.

<dialog>
  <p>This is da dialog!</p>
  <button id="close">Close</button>
</dialog>
<button id="show">Open Dialog!</button>
<script>
  var dialog = document.querySelector('dialog');
  document.querySelector('#show').onclick = function() {
    dialog.show();
  };
  document.querySelector('#close').onclick = function() {
    dialog.close();
  };
</script>

Check out more sample codes and how it works in detail with a live demo.

There are a few changes applied to the implementation since the last announcement but notable one is:

  • Non-modal <dialog> is no longer vertically centered in the viewport. It has no special positioning behavior beyond its default CSS styling.

If you are curious about further details on the spec update, check out diffs here and here.


Blob support for IndexedDB landed on Chrome Dev

Chrome Dev has landed support for Blob on IndexedDB.

This is a long awaited feature for Chrome that allows IndexedDB API to be able to store and retrieve a Blob without converting it to a Base64 string.

IndexedDB provides large scale key-value type persistent storage that is available on most of modern browsers (Safari apparently will land support in iOS8 and Mac OS X 10.10). Check out its implementation status.

Blob is a file-like binary object modern JavaScript engines can handle. File objects inherits from Blob. You can also fetch images and files as Blob via XMLHttpRequest. Check out its implementation status.

Storing a Blob on IndexedDB

There is no way to feature detect the Blob availability in IndexedDB. You basically have to try-catch then use string instead of Blob if it is not available. Here's some sample code:

// Create an example Blob object
var blob = new Blob(['blob object'], {type: 'text/plain'});

try {
  var store = db.transaction(['entries'], 'readwrite').objectStore('entries');

  // Store the object  
  var req = store.put(blob, 'blob');
  req.onerror = function(e) {
    console.log(e);
  };
  req.onsuccess = function(event) {
    console.log('Successfully stored a blob as Blob.');
  };
} catch (e) {
  var reader = new FileReader();
  reader.onload = function(event) {
    // After exception, you have to start over from getting transaction.
    var store = db.transaction(['entries'], 'readwrite').objectStore('entries');

    // Obtain DataURL string
    var data = event.target.result;
    var req = store.put(data, 'blob');
    req.onerror = function(e) {
      console.log(e);
    };
    req.onsuccess = function(event) {
      console.log('Successfully stored a blob as String.');
    };
  };
  // Convert Blob into DataURL string
  reader.readAsDataURL(blob);
}

Blob support for IndexedDB is already available on Firefox and Internet Explorer as well. Safari support needs to be investigated.

Enjoy!


DevTools Digest - Chrome 35: Updates to the Developer Tools in Chrome 35

Updates to the Chrome Developer Tools: CSS property quick search, memory stats for heap snapshots, CodeMirror upgrade and more.


Automating Web Performance Measurement

Web performance can have a huge impact on your entire user experience. If you?ve been looking at improving your own site?s perf lately, you?ve probably heard of PageSpeed Insights - a tool that analyzes pages and offers advice on how to make them faster based on best practices for mobile and desktop web performance.

PageSpeed?s scores are based on a number of factors, including how well your scripts are minimized, images optimized, content gzipped, tap targets being appropriately sized and landing page redirects avoided.

With 40% of people potentially abandoning pages that take more than 3 seconds to load, caring about how quickly your pages load on your users devices is increasingly becoming an essential part of our development workflow.

Performance metrics in your build process

Although manually going to the PageSpeed Insights to find out how your scores is fine, a number of developers have been asking whether it's possible to get similar performance scoring into their build process.

The answer is: absolutely.

Introducing PSI for Node

Today we?re happy to introduce PSI for Node - a new module that works great with Gulp, Grunt and other build systems and can connect up to the PageSpeed Insights service and return a detailed report of your web performance. Let?s look at a preview of the type of reporting it enables:

The results above are good for getting a feel for the type of improvements that could be made. For example, a 5.92 for sizing content to viewport means ?some? work can still be done whilst a 24 for minimizing render blocking resources may suggest you need to defer loading of JS using the async attribute.

Lowering the barrier of entry to PageSpeed Insights

If you've tried using the PageSpeed Insights API in the past or attempted to use any of the tools we build on top of it, you probably had to register for a dedicated API key. We know that although this just takes a few minutes, it can be a turn off for getting Insights as part of your regular workflow.

We're happy to inform you that the PageSpeed Insights service supports making requests without an API key for up to 1 request every 5 seconds (plenty for anyone). For more regular usage or serious production builds, you'll probably want to register for a key.

The PSI module supports both a nokey option for getting it setup in less than a few minutes and the key option for a little longer. Details on how to register for an API key are documented.

Getting started

You have two options for how you integrate PSI into your workflow. You can either integrate it into your build process or run it as a globally installed tool on your system.

Build process

Using PSI in your Grunt or Gulp build-process is fairly straight-forward. If you?re working on a Gulp project, you can install and use PSI directly.

Install

Install PSI using npm and pass --save-dev to save it to your package.json file.

npm install psi --save-dev

Then define a Gulp task for it in your gulpfile as follows (also covered in our Gulp sample project):

   var psi = require('psi');
   gulp.task('psi', function (cb) {
       psi({
           nokey: 'true', // or use key: ?YOUR_API_KEY?
           url: site,
           strategy: 'mobile',
       }, cb);
   });
   

For the above, you can then run the task using:

gulp psi

And if you?re using Grunt, you can use grunt-pagespeed by James Cryer which now uses PSI to power it?s reporting.

Install

npm install grunt-pagespeed --save-dev

Then load the task in your Gruntfile:

grunt.loadNpmTasks('grunt-pagespeed');

and configure it for use:

   pagespeed: {
     options: {
       nokey: true,
       url: "https://www.html5rocks.com",
       strategy: "mobile"
     }
   }
   

You can then run the task using:

grunt pagespeed

Installing as a global tool

You can also install PSI as a globally available tool on your system. Once again, we can use npm to install the tool:

$ npm install -g psi

And via any terminal window, request PageSpeed Insights reports for a site (with the nokey option or an API specific key as follows):

psi http://www.html5rocks.com --nokey --strategy=mobile

or for those with a registered API key:

psi http://www.html5rocks.com --key=YOUR_API_KEY --strategy=mobile

That?s it!

Go forth and make performance part of your culture

We need to start thinking more about the impact of our designs and implementations on user experience.

Solutions like PSI can keep an eye on your web performance on desktop and mobile and are useful when used as part of your regular post-deployment workflow.

We're eager to hear of any feedback you might have and hope PSI helps improve the performance culture on your team.


Web Animations - element.animate() is now in Chrome 36

Animation on the web was once the province of JavaScript, but as the world moved to mobile, animations moved to CSS for the declarative syntax and the optimizations browsers were able to make with it. With 60fps on mobile always your goal, it makes sense to never step outside of what browsers know how to efficiently display.

More tools are appearing to make JavaScript-driven animations more efficient, but the holy grail is a unification of declarative and imperative animations , where the decision of how to write your animations is based on what’s the clearest code, not what is possible in one form and not in the other.

Web Animations stand to answer that call, and the first part of it has landed in Chrome 36 in the form of element.animate(). This new function lets you create an animation purely in JavaScript and have it run as efficiently as any CSS Animation or Transition (in fact, as of Chrome 34, the exact same Web Animations engine drives all of these methods).

The syntax is simple, and its parts should be familiar to you if you’ve ever written a CSS Transition or Animation:

element.animate([
  {cssProperty: value0},
  {cssProperty: value1},
  {cssProperty: value2},
  //...
], {
    duration: timeInMs,
    iterations: iterationCount,
    delay: delayValue
});

The biggest advantage of this new function is the elimination of a lot of awkward hoops we formerly had to jump through to get a smooth, jank-free animation.

As an example, for Santa Tracker last year, we wanted to have snow falling continuously, and we decided to animate it via CSS so that it could be done so efficiently.

However, we wanted to pick the snow’s horizontal position dynamically based on screen and events going on in the scene itself, and of course the height of the snow’s fall (the height of the user’s browser window) wouldn’t be known until we were actually running. This meant we really had to use CSS Transitions, as authoring a CSS Animation at runtime gets complex quickly (and hundreds of snowflakes means hundreds of new styling rules).

So we took the following approach, which should be familiar:

snowFlake.style.transform = 'translate(' + snowLeft + 'px, -100%)';
// wait a frame
snowFlake.offsetWidth;
snowFlake.style.transitionProperty = 'transform';
snowFlake.style.transitionDuration = '1500ms';
snowFlake.style.transform = 'translate(' + snowLeft + 'px, ' + window.innerHeight + 'px)';

The key is in that 'wait a frame’ comment. In order to successfully start a transition, the browser has to acknowledge that the element is in the starting position. There are a few ways to do this. One of the most common ways is to read from one of the element properties that forces the browser to compute layout, thereby ensuring it knows that the element has a starting position before transitioning to the ending position. Using this method allows you to congratulate yourself on your superior knowledge of browser internals while still feeling dirty with every keystroke.

In contrast, the equivalent `element.animate()` call couldn’t be more clear, saying exactly what is intended:

snowFlake.animate([
  {transform: 'translate(' + snowLeft + 'px, -100%)'},
  {transform: 'translate(' + snowLeft + 'px, ' + window.innerHeight + 'px)'}
], 1500);

There are many more options. Just like with its CSS counterparts, Web Animations can be delayed and iterated:

snowFlake.animate([
  {transform: 'translate(' + snowLeft + 'px, -100%)'},
  {transform: 'translate(' + snowLeft + 'px, ' + window.innerHeight + 'px)'}
], {
  duration: 1500,
  iterations: 10,
  delay: 300
});

AnimationPlayer

element.animate() actually returns an AnimationPlayer object, which will become increasingly important as more of the Web Animations spec is launched. Both JavaScript- and CSS-created animations will have associated AnimationPlayers, allowing them to be seamlessly combined in useful and interesting ways.

For now, though, AnimationPlayer only has two pieces of functionality, both very useful. You can cancel an animation at any time by using AnimationPlayer.cancel():

var player = snowFlake.animate([
  {transform: 'translate(' + snowLeft + 'px, -100%)'},
  {transform: 'translate(' + snowLeft + 'px, ' + window.innerHeight + 'px)'}
], 1500);
// less than 1500ms later...changed my mind
player.cancel();

And, to the relief of everyone who has attempted to build an animation system around CSS Animations or Transitions in the past, Web Animations always fire an event when they’re finished:

var player = snowFlake.animate([
  {transform: 'translate(' + snowLeft + 'px, -100%)'},
  {transform: 'translate(' + snowLeft + 'px, ' + window.innerHeight + 'px)'}
], 1500);
player.onfinish = function(e) {
  console.log('per aspera ad terra!');
}

Try it out

This is all shipping in Chrome 36, moving to beta today! If you’d like to try it, try working with the native implementation in Chrome 36. However, there is a Web Animations polyfill, which brings a significantly larger part of the full Web Animations specification to any of the modern, evergreen browsers.

A demo of the snow effect is available for you to try using both the native version of element.animate() and the polyfill.

Let us know what you think

Really, though, this is a preview of what’s to come, and is being released specifically to get developer feedback right away. We’re not sure yet if we’ve hit every use case, or sanded down every rough edge of the current APIs for animation. The only way for us to know and to really get this right is for developers to try it out and let us know what they think.

Comments on this post are of course valuable, and comments on the standard itself can be addressed to the CSS and SVG Working Groups via the public-fx mailing list.

Thanks to Addy Osmani and Max Heinritz for their assistance with this post.


A More Compatible, Smoother Touch

You and your users want mobile web apps that react and scroll smoothly to the touch. Developing them should be easy but, unfortunately, how mobile web browsers react to touch events during scrolling is left as an implementation detail in the TouchEvent specification. As a result, approaches can be broken down roughly into 4 categories. This situation exposes a fundamental tension between delivering scroll smoothness and maintaining developer control.

Four different models of touch event processing?

The behavior differences between the browsers break down into four models.

  1. Normal synchronous event processing

    Touchmove events are sent during scrolling and each scroll update blocks until touchmove handling has completed. This is good as the simplest to understand and the most powerful but bad for scroll performance because it means that each frame during the scroll must block on the main thread.

    Browsers: Android Browser (Android 4.0.4, 4.3), Mobile Safari (when scrolling div)

  2. Asynchronous touchmove processing

    Touchmove events are sent during scrolling, but scrolling can proceed asynchronously (the touchmove event is ignored after scrolling has begun). This can result in "double handling" of events, for example, continuing to scroll after the web site does something with the touchmove and calls preventDefault on the event, telling the browser not to handle it.

    Browsers: Mobile Safari (when scrolling Document), Firefox

  3. Touchmove suppressed while scrolling

    Touchmove events are not sent after scrolling starts and do not resume until after the touchend event. In this model, it's hard to tell the difference between a stationary touch and a scroll.

    Browsers: Samsung Browser (mousemove events sent)

  4. Touchcancel on scroll start

    You can't have it both ways -- scroll smoothness and developer control -- and this model makes clear the trade-off between smooth scrolling and event handling, similar to the semantics of the Pointer Events specification. Some experiences that may need to track the finger, like pull-to-refresh, are not possible.

    Browsers: Chrome Desktop M32+, Chrome Android

Why Change?

Chrome for Android currently uses Chrome's Old Model: touchcancel on scroll start, which enhances scrolling performance, but leads to developer confusion. In particular, some developers aren't aware of the touchcancel event or how to deal with it, and this has caused some web sites to break. More importantly, an entire class of UI scrolling effects and behaviors, such as pull-to-refresh, hidey bars, and snap points are difficult or impossible to implement well.

Rather than adding specifically hardcoded features to support these effects, Chrome aims to concentrate on adding platform primitives that allow developers to implement these effects directly. See A Rational Web Platform for a general exposition of this philosophy.

Chrome's New Model: The Throttled Async Touchmove Model

Chrome is introducing a new behavior designed to improve compatibility with code written for other browsers when scrolling, as well as enabling other scenarios that depend on getting touchmove events while scrolling. This feature is enabled by default and you can turn it off with the following flag, chrome://flags#touch-scrolling-mode.

The new behavior is:

  • The first touchmove is sent synchronously to allow scroll to be canceled
  • During active scrolling
    • touchmove events are sent asynchronously
    • throttled to 1 event per 200ms, or if a CSS 15px slop region is exceeded
    • Event.cancelable is false
  • Otherwise, touchmove events fire synchronously as normal when active scrolling terminates or isn't possible because the scroll limit has been hit
  • A touchend event always occurs when the user lifts their finger

You can try this demo in Chrome for Android and toggle the chrome://flags#touch-scrolling-mode flag to see the difference.

Let us know what you think

The Async Touchmove Model has the potential to improve cross-browser compatibility and enable a new class of touch gesture effects. We're interested in hearing what developers think, and in seeing the creative things you can do with it.


Data-binding Revolutions with Object.observe()

Learn about Object.observe() - a new feature giving JavaScript the power to directly observe changes to objects.


Debugging Asynchronous JavaScript with Chrome DevTools

Up your JavaScript debugging kung fu with asynchronous call stack traces in the Chrome DevTools.


Build with Chrome: Bringing LEGOŽ bricks to the Multi-Device Web

The Build With Chrome team redesigned the site to support both mouse and touch input.


DevTools Digest: Updates to the Developer tools in Chrome 33

Updates to the Chrome Developer Tools: async call stacks, edit locations, goto :line:column



@2014 CompCoding.com