Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Monday, January 30, 2012

Translating JavaScript to Dart

Marcin
Aaron

By Aaron Wheeler, Senior User Experience Prototyper, and Marcin Wichary, Senior User Experience Designer

Cross-posted with the Chromium Blog

It took approximately 2000 years for the original Rosetta Stone to be discovered, which helped translate the Egyptian Hieroglyphs. We couldn’t wait that long to bridge the Dart and JavaScript worlds, so today we are releasing the JavaScript to Dart Synonym app.

Like most web developers, we are familiar, comfortable, and productive with JavaScript. We were curious about Dart, and thanks to a recent Dart hackathon, we had the chance to play with the language and libraries. The problem was, as JavaScript developers, we didn’t know how to map common JavaScript idioms to Dart. Hence the idea for this synonym app was born.

We started with the basics that every JavaScript and jQuery developer knows: variables, arrays, functions, classes, DOM manipulation, and many more. Then, with the help of the Dart team, we recorded the corresponding Dart versions of each idiom. To practice what we learned, we wrote this app with Dart.



We hope our app that maps between JavaScript and Dart eases your introduction to Dart and gives you a sense of where the project is going. We know the team is eager to hear your feedback. Don’t hesitate to join the conversation or file a new issue for either Dart or the Synonym app. And remember, Dart isn’t set in stone, so your feedback counts.


Aaron Wheeler is a user experience prototyper working on special projects that go beyond the Web. He balances design and engineering outside of work as well, splitting time between artistic pursuits and bicycle maintenance.

Marcin Wichary is a user experience designer, currently working on the Chrome browser and thinking of the future of the Web platform. He also occasionally codes interactive homepage doodles, such as Pac-Man and Stanislaw Lem.

Posted by Scott Knaster, Editor

Wednesday, November 30, 2011

JavaScript Client Library for Google APIs Alpha version released

author photo
Brendan
author photo
Antonio
By Brendan O’Brien and Antonio Fuentes, Google Developer Team

Today we reached another milestone in our efforts to provide infrastructure and tools to make it easier for developers to use Google APIs: we have released the Google APIs Client Library for JavaScript in Alpha. This client library is the latest addition to our suite of client libraries, which already includes Python, PHP, and Java.

This compact and efficient client library provides access to all the Google APIs that are listed in the APIs Explorer. The client library is also flexible, supporting multiple browser environments including Chrome 8+, Firefox 3.5+, Internet Explorer 8+, Safari 4+, and Opera 11+. In addition, the JavaScript client library supports OAuth 2.0 authorization methods.

You can load the client library using the following script tag:
<script src="https://apis.google.com/js/client.js?onload=CALLBACK"></script>
Loading an API and making a request is as easy as executing:
gapi.client.load('API_NAME', 'API_VERSION', CALLBACK); // Returns a request object which can then be executed. // METHOD_NAME is only available once CALLBACK runs. var request = gapi.client.METHOD_NAME(PARAMETERS_OBJECT); request.execute(callback);
You can use the APIs Explorer to check all the methods available for an API, as well as the parameters for each method. For instance, use the above syntax with the plus.activities.search method of the Google+ API to query activities:

<!DOCTYPE html> <html>  <head>  </head>  <body>    <script type="text/javascript"> function init() {  // Load your API key from the Developer Console  gapi.client.setApiKey('YOUR_API_KEY');  // Load the API  gapi.client.load('plus', 'v1', function() {      var request = gapi.client.plus.activities.search({          'query': 'Google+',            'orderby': 'best'            });      request.execute(function(resp) {          // Output title          var heading = document.createElement('h4');          heading.appendChild(document.createTextNode( resp.title));          var content = document.getElementById('content');          content.appendChild(heading);          // Output content of the response          if (!resp.items) {            content.appendChild(document.createTextNode( 'No results found.'));          } else {            for (var i = 0; i < resp.items.length; i++) {              var entry = document.createElement('p');            entry.appendChild(document.createTextNode( resp.items[i].title));              content.appendChild(entry);            }          }        });    }); }    </script>    <script src="https://apis.google.com/js/client.js?onload=init"></script>    <div id="content"></div>  </body> </html>
To try this yourself, sign up in the Google APIs console or refer to the documentation on acquiring and using a developer key in the Google+ API.

The Google APIs Client Library for JavaScript is currently in Alpha, which means that we are actively developing it, but wanted to get the library in your hands as soon as possible, and we welcome any feedback to make the code better. While you can use the current library to start writing code, you should use caution when writing production code as library code changes may break your application. We are working hard to upgrade this release to Beta and beyond soon, and to release even more client libraries.

To get started, visit the JavaScript Client Library documentation page. We also welcome your feedback, which you can provide using the JavaScript client group.


Brendan O'Brien is a Software Engineer for the Browser Client group at Google. Prior to working on JavaScript APIs he was a frontend engineer for iGoogle. He is passionate about JavaScript and enjoys building web applications.

Antonio Fuentes is a Product Manager for the Google API Infrastructure group. He has experience launching products in the cloud computing, infrastructure, and virtualization space.

Posted by Scott Knaster, Editor

Monday, May 09, 2011

Creating 2D Games with JavaScript & HTML5


By Dominic Szablewski, creator of the Impact Game Engine

This post is part of Who's at Google I/O, a series of guest blog posts written by developers who are appearing in the Developer Sandbox at Google I/O.


Impact is a JavaScript game engine that uses the HTML5 Canvas and Audio elements for graphics and sound, instead of relying on any browser plugins. Impact's main focus is on classic 2D games. Examples include the Biolab Disaster Jump'n'Run game and the Z-Type Space Shooter. These games, like many other 2D games, draw sprites in front of multiple background layers.


Each background layer is drawn from a tileset, an image containing all the individual building blocks, and a tilemap, a 2D array that tells the renderer where to draw each of these tiles. Similarly, sprites are drawn from an animation sheet, an image with all the animation's frames.

This technique has proven so efficient and flexible that it was enforced in hardware on early game consoles: the Super Nintendo could not do anything other than draw tiled background maps and sprites. There was no way to directly access single pixels on the screen.

The HTML5 Canvas element is perfectly equipped for these kinds of games. Most importantly, the Canvas API's drawImage() method allows us to draw only a certain part of a tileset or animation sheet to the screen. In Impact, however, you don't have to deal with any of the Canvas API methods directly. Instead, you specify your tilemaps and animation sheets and let the engine handle the details.

This is how you'd create an animation from an animation sheet:


// Each animation frame is 16x16 pixels
var sheet = new ig.AnimationSheet( 'player.png', 16, 16 );

// This creates the "run" animation: it has 6 frames (the 2nd row 
// in the image), with each one being shown for 0.07 seconds
var run = new ig.Animation( sheet, 0.07, [6,7,8,9,10,11] );
Similarly, here's the code needed to create and draw a background layer:
// Create a 2D tilemap
var map = [
 [5, 3, 4],
 [2, 7, 1],
 [6, 0, 3]
];

// Specify a layer with a tilesize of 16px and our tilemap
var layer = new ig.BackgroundMap( 16, map, 'tileset.png' );
layer.draw();
You don't have to create these tilemaps by hand. Impact comes with a powerful level editor called Weltmeister, which makes it easy to draw background layers and position your entities (non-static objects in the game world) in your levels.


When drawing on a Canvas, the performance is mostly bounded by the number of draw calls. It is far more efficient to draw one or two very large images than to draw several hundred small ones. This means that drawing background layers tile by tile can be quite slow, especially on mobile devices.

The Impact engine therefore has a special "pre-render" mode that you can enable on background layers. This mode will first draw the tilemap into large chunks of 512x512 pixels when loading a level, and then use these chunks to fill the screen instead of drawing the layer tile by tile. With this technique, you can get good frame rates even for fast-paced games on Android and iOS devices.

Impact also handles sound, input, timing, and much more for you. It's by no means a game engine that can do everything – and it doesn't try to be one – but it's very good at the things it can do.


Come see Impact in the Developer Sandbox at Google I/O on May 10-11.

Dominic Szablewski is the creator of the Impact Game Engine. He recently finished his Bachelor Thesis about HTML5 Gaming and now lives the dream by selling Impact and making games.

Posted by Scott Knaster, Editor

Monday, April 04, 2011

A new test suite for rich text editing


This post is by Roland Steiner of the Chrome Team. Roland works mainly on layout and rendering for Chrome and WebKit. An Austrian native, Roland has ventured far and made Tokyo his second home. -scottk

Many web applications allow users not just to edit plain text, but also to embellish it – making it bold or underlined, adding bulleted lists or images. For example, think of online document or blog editors, or rich e-mail apps. JavaScript provides various APIs you can use to implement these apps.

Unfortunately, while these APIs are largely defined the same in modern browsers, the results often differ. To document the current state of all this, we have set up a new rich text editing test suite as part of the larger browserscope framework.

Let’s look at how a region of text, such as a <div>, can be marked as editable by adding the contenteditable attribute:
<div contenteditable="true"> ...some content... </div>
You can then manipulate the content with simple calls:
document.execCommand("formatting command", showUI, parameter)
For example, you can set the color of the selected text to red with this call:
document.execCommand("forecolor", false, "red")
Although this command works well on most browsers, different browsers implement different subsets of formatting commands, and even common commands often produce varying HTML structures.

There are other APIs that affect selection and cursor movement, or allow querying of the current state, and those, too, are often implemented differently.

Our new test suite tries to capture all currently implemented commands and APIs, and runs them on varying initial HTML content and within various containers. The suite already contains well over 1,000 tests.


We don’t want to stop there. We intend to grow the suite and incorporate external feedback and suggestions so we can arrive at a common set of editing functions. We hope this can then serve as a common reference, not only for browser implementers, but also for web developers.

To achieve this goal, we would like input from anyone interested in this topic, including those with past complaints about bugs and incompatibilities in this area.

For suggestions, criticism, and general discussion on the suite and tests, please send feedback to the browserscope mailing list at [email protected].

Monday, November 15, 2010

Instant Previews: Under the hood

If you’ve used Google Search recently, you may have noticed a new feature that we’re calling Instant Previews. By clicking on the (sprited) magnifying glass icon next to a search result you see a preview of that page, often with the relevant content highlighted. Once activated, you can mouse over the rest of the results and quickly (instantly!) see previews of those search results, too.

Adding this feature to Google Search involved a lot of client-side Javascript. Being Google, we had to make sure we could deliver this feature without slowing down the page. We know our users want their results fast. So we thought we’d share some techniques involved in making this new feature fast.

JavaScript compilation

This is nothing new for Google Search: all our Javascript is compiled to make it as small as possible. We use the open-sourced Closure Compiler. In addition to minimizing the Javascript code, it also re-writes expressions, reuses variables, and prunes out code that is not being used. The Javascript on the search results page is deferred, and also cached very aggressively on the client side so that it’s not downloaded more than once per version.

On-demand JSONP

When you activate Instant Previews, the result previews are requested by your web browser. There are several ways to fetch the data we need using Javascript. The most popular techniques are XmlHttpRequest (XHR) and JSONP. XHR generally gives you better control and error-handling, but it has two drawbacks: browsers caching tends to be less reliable, and only same-origin requests are permitted (this is starting to change with modern browsers and cross-origin resource sharing, though). With JSONP, on the other hand, the requested script returns the desired data as a JSON object wrapped in a Javascript callback function, which in our case looks something like

google.vs.r({"dim":[302,585],"url":"http://example.com",ssegs:[...]}).

Although error handling with JSONP is a bit harder to do compared to XHR (not all browsers support onerror events), JSONP can be cached aggressively by the browser, and is not subject to same-origin restrictions. This last point is important for Instant Previews because web browsers restrict the number of concurrent requests that they send to any one host. Using a different host for the preview requests means that we don’t block other requests in the page.

There are a couple of tricks when using JSONP that are worth noting:

  • If you insert the script tag directly, e.g. using document.createElement, some browsers will show the page as still “loading” until all script requests are finished. To avoid that, make your DOM call to insert the script tag inside a window.setTimeout call.
  • After your requests come back and your callbacks are done, it’s a good idea to set your script src to null, and remove the tag. On some browsers, allowing too many script tags to accumulate over time may slow everything down.

Data URIs

At this point you are probably curious as to what we’re returning in our JSONP calls, and in particular, why we are using JSON and not just plain images. Perhaps you even used Firebug or your browser’s Developer Tools to examine the Instant Previews requests. If so, you will have noticed that we send back the image data as sets of data URIs. Data URIs are base64 encodings of image data, that modern browsers (IE8+, Chrome, Safari, Firefox, Opera, etc) can use to display images, instead of loading them from a server as usual.

To show previews, we need the image, and the relevant content of the page for the particular query, with bounding boxes that we draw on top of the image to show where that content appears on the page. If we used static images, we’d need to make one request for the content and one request for the image; using JSONP with data URIs, we make just one request. Data URIs are limited to 32K on IE8, so we send “slices” that are all under that limit, and then use Javascript to generate the necessary image tags to display them. And even though base64 encoding adds about 33% to the size of the image, our tests showed that gzip-compressed data URIs are comparable in size to the original JPEGs.

We use caching throughout our implementation, but it’s important to not forget about client-side caching as well. By using JSONP and data URIs, we limit the number of requests made, and also make sure that the browser will cache the data, so that if you refresh a page or redo a query, you should get the previews, well... instantly!

Thursday, September 16, 2010

Google Relaunches Instantiations Developer Tools - Now Available for Free

(Cross-posted from the Google Web Toolkit blog)

In early August, Google acquired Instantiations, a company known for its focus on Eclipse Java developer tools, including GWT Designer. We're happy to announce today that we're relaunching the following former Instantiations products under the Google name and making them available to all developers at no charge:

  • GWT Designer
    Powerful Eclipse-based development tools that enable Java developers to quickly create Ajax user interfaces using Google Web Toolkit (GWT)

  • CodePro AnalytiX
    Comprehensive automated software code quality and security analysis tools to improve software quality, reliability, and maintainability

  • WindowBuilder Pro
    Java graphical user interface designer for Swing, SWT, GWT, RCP, and XWT UI frameworks

  • WindowTester Pro
    Test GUI interactions within Java client rich applications for the SWT and Swing UI frameworks

Now that these products are available again, we hope you’ll start using them within your GWT projects. Meanwhile, our next step is to more deeply unify them into the GWT family of tools by blending the fantastic Instantiations technology into the Google Plugin for Eclipse (GPE). So, there’s much more to come, including things we’re pretty sure you’ll like, such as UiBinder support in GWT Designer.

You can download any of the tools from the GWT download page. If you have questions or comments we’d love to hear from you. The best place to discuss the tools above is at http://forums.instantiations.com. As always, continue to discuss GWT and GPE at the main GWT Group.

We would love to stay in better touch with you as we have more news about how we are integrating the Instantiations products into the Google Web Toolkit suite. Sign up if you’d like to receive email updates on these products and other developer tools.

Tuesday, June 15, 2010

Reversing Code Bloat with the JavaScript Knowledge Base

JavaScript libraries let developers do more with less code. But JavaScript libraries need to work on a variety of browsers, so using them often means shipping even more code. If JQuery has code to support XMLHttpRequest over ActiveX on an older browser like IE6 then you end up shipping that code even if your application doesn't support IE6. Not only that, but you ship that code to the other 90% of newer browsers that don't need it.


This problem is only going to get worse. Browsers are rushing to implement HTML5 and EcmaScript5 features like JSON.parse that used to be provided only in library code, but libraries will likely have to keep that code for years if not decades to support older browsers.


Lots of compilers (incl. (JSMin, Dojo, YUI, Closure, Caja) remove unnecessary code from JavaScript to make the code you ship smaller. They seem like a natural place to address this problems. Optimization is just taking into account the context that code is going to run in to improve it; giving compilers information about browsers will help them avoid shipping code to support marginal browsers to modern browsers.

The JavaScript Knowledge Base (JSKB) on browserscope.org seeks to systematically capture this information in a way that compilers can use.

It collects facts about browsers using JavaScript snippet. The JavaScript code (!!window.JSON && typeof window.JSON.stringify === 'function') is true if JSON is defined. JSKB knows that this is true for Firefox 3.5 but not Netscape 2.0.

Caja Web Tools includes a code optimizer that uses these facts. If it sees code like

if (typeof JSON.stringify !== 'function') { /* lots of code */ }

it knows that the body will never be executed on Firefox 3.5, and can optimize it out. The key here is that the developer writes feature tests, not version tests, and as browsers roll out new features, JSKB captures that information, letting compilers produce smaller code for that browser.


The Caja team just released Caja Web Tools, which already uses JSKB to optimize code. We hope that other JavaScript compilers will adopt these techniques. If you're working on a JavaScript optimizer, take a look at our JSON APIs to get an idea of what the JSKB contains.


If you're writing JavaScript library code or application code then the JSKB documentation can suggest good feature tests. And the examples in the Caja Web Tools testbed are good starting places.


Thursday, May 27, 2010

Chrome Extensions for Web Development

The Chrome Developer Tools are great for debugging HTML, JavaScript and CSS in Chrome. If you're writing a webpage or even a web app for the Chrome Web Store, you can inspect elements in the DOM, debug live JavaScript, and edit CSS styles directly in the current page. Extensions can make Google Chrome an even better web development environment by providing additional features that you can easily access in your browser. To help developers like you, we created a page that features extensions for web development. We hope you’ll find them useful in creating applications and sites for the web.


For example, Speed Tracer is an extension to help you identify and fix performance issues in your web applications. With Speed Tracer, you can get a better idea of where time is being spent in your application and troubleshoot problems in JavaScript parsing and execution, CSS style, and more.


Another useful extension is the Resolution Test that changes the size of the browser window, so web developers can preview websites in different screen resolutions. It also includes a list of commonly used resolutions, as well as a custom option to input your own resolution.


With the Web Developer extension, you can access additional developer tools such as validation options, page resizing and a CSS elements viewer; all from an additional button in the toolbar.


Another extension you should check out is the Chrome Editor that allows you to easily code within your browser, so you don’t have to flip between your browser and code editor. You can also save a code reference locally to your computer for later use.

These are just a few of the extensions you can find in our extensions for web development page. You can also look for more in the extensions gallery.

Monday, April 19, 2010

Using XAuth to simplify the social web

Earlier today Meebo announced Extended Authentication (XAuth), an open platform that makes it possible for users to bring their preferred services with them across the web.

To learn more about XAuth and why we're among the supporters of this technology, check out our post on the Social Web Blog.

From a technical perspective, we wanted to offer you some additional insights into how this technology works.

If you visit Meebo's XAuth page, you should see an array of logos:


When this page loaded, it requests the list of services that have been registered with XAuth by making an HTML5 window.postMessage request to xauth.org. As you can see in the graphic, no active sessions were detected.

When the user clicks through to one of the linked demo pages — we'll use googxauthdemo.appspot.com in this case — the same JavaScript is loaded from xauth.org. When the user successfully authenticates, some basic information is pushed to the browser's HTML5 localStorage:

<script type="text/javascript">
function doLogin(doneUrl) {
/* Tell XAuth.org that a user has just signed into Google on this browser. */
XAuth.extend({
// reveals "someone is logged into Google"
token: "1",
// Expires after 24 hours or if the user explicitly logs out
expire: new Date().getTime() + 60*60*24*1000,
// Allow any domain to read this info (could also be a whitelist of partners)
extend: ["*"],
// Optional callback function once extend() has completed.
callback: makeRedirectFunc(doneUrl)
});
}
</script>

This information — that the user has an active session at googxauthdemo.appspot.com — is now available to any site on the web (because extend: ["*"] uses the wildcard case to make this information world-readable; providers can also choose to restrict access to this information to certain domains or partners).

Upon returning to meebo.com/xauth, the page requests the list of active sessions from XAuth, and passes the browser an array of domains that the browser will match against the local storage for xauth.org:

<script type="text/javascript">
XAuth.retrieve({
retrieve: ['xauth.org', 'googxauthdemo.appspot.com', 'xauthdemo.mslivelabs.com'],
callback: receiveTokens }
);
</script>

The major performance and scalability benefits of this design are a result of the single HTTP request made to xauth.org to determine which services are currently active, rather than one-request-per-domain. The request and response are also purely client-side, so there's no waiting for a server to look up anything in a database — and the XAuth JavaScript files get cached after they are first retrieved, making XAuth overall very efficient.

Once the tokens are retrieved the program iterates through them looking for matches, and then modifies the interface according the service token discovered, like this:

<script type="text/javascript">
function receiveTokens(responseObj) {
var tokens = responseObj.tokens;
var token = tokens['xauth.org'];
var partners = {};
var tokensFound = false;
if (tokens['googxauthdemo.appspot.com']) {
partners['google'] = true;
tokensFound = true;
var status = document.getElementById('status-google');
status.innerHTML = 'Signed In!';
status.style.color = '#0A0';
}
}
</script>

In this way, site publishers can detect a user's set of active and preferred services, or request a subset of known services, and present only those services which are known to be currently active. In practice, the list of services provided at any given time by xauth.org should not be considered exhaustive, but instead a suggestion for how to prioritize complex service selection dialogs and interfaces, like those known as "NASCAR" interfaces.

For more technical information about XAuth, please read the spec, or visit the informational page on xauth.org.