Caridy - Random Bubbles http://caridy.name Javascript, YUI, Mojito and Web Applications Sat, 08 Dec 2012 03:38:21 +0000 en hourly 1 http://wordpress.org/?v=3.3.1 YUIConf 2012: Mojito for YUI Developers (video) http://caridy.name/2012/12/yuiconf2012-mojito-for-yui-developers/ http://caridy.name/2012/12/yuiconf2012-mojito-for-yui-developers/#comments Sat, 08 Dec 2012 03:35:59 +0000 caridy http://caridy.name/?p=307 When/Where: Nov 14th 2012, YUIConf in Santa Clara, CA.

We use YUI on the daily basis in a form of building blocks, but when it comes to boilerplating our projects, we are on our own. Mojito provides a unique opportunity for YUI developers to speed up the development process by providing boilerplate and building capabilities for YUI projects by offering a variety of options to build traditional YUI web apps, mobile apps to deploy on devices, and Node.JS applications as well. It does it by leveraging YUI Library and YUI Tool chains to build at scale.

Here is the recorded video:

Here are the slides:

]]>
http://caridy.name/2012/12/yuiconf2012-mojito-for-yui-developers/feed/ 0
Webinar: YUI Configuration within Mojito http://caridy.name/2012/08/webinar-yui-configuration-within-mojito/ http://caridy.name/2012/08/webinar-yui-configuration-within-mojito/#comments Fri, 10 Aug 2012 16:02:37 +0000 caridy http://caridy.name/?p=300

HD Video

Topics covered in this screencast:

  • Mojito 0.4.0 (boiler plate for app and simple mojit)
  • Application.json specs and mojit instances
  • Simple routes
  • Controlling the YUI logs in mojito
  • Custom setting for “dependencyCalculations”
  • Requiring modules that are computed automatically
  • The YUI_config object in mojito
  • Development vs Production settings to facilitate debugging
  • How to use YUI Console in mojito
  • Other recommended settings for

Original Code:

More info about some of the topics mentioned in the screencast:

]]>
http://caridy.name/2012/08/webinar-yui-configuration-within-mojito/feed/ 0
Webinar: Custom and secure settings in Mojito http://caridy.name/2012/08/webinar-custom-and-secure-settings-in-mojito/ http://caridy.name/2012/08/webinar-custom-and-secure-settings-in-mojito/#comments Fri, 03 Aug 2012 01:46:59 +0000 caridy http://caridy.name/?p=286

HD Video

Topics covered in this screencast:

  • Mojito 0.3.30 (boiler plate for app and simple mojit)
  • Application.json specs and mojit instances
  • Simple routes
  • Configuration per mojit instance
  • Security risks when using configurations
  • Defaults.json to define basic configurations
  • The runtime server configuration to protect your settings and routes
  • Edge case to have protected global settings per mojit instance

Original Code:

More info about some of the topics mentioned in the screencast:

]]>
http://caridy.name/2012/08/webinar-custom-and-secure-settings-in-mojito/feed/ 0
BayJax Presentation: Expanding Yahoo! Axis Across 3 Screens http://caridy.name/2012/07/expanding-yahoo-axis-across-3-screens/ http://caridy.name/2012/07/expanding-yahoo-axis-across-3-screens/#comments Fri, 13 Jul 2012 01:18:16 +0000 caridy http://caridy.name/?p=278 When/Where: June 25th, 2012, BayJax at Yahoo! Campus in Sunnyvale, CA.

Discussing Yahoo!’s new search browser experience, the Yahoo! Axis, and the challenges involved in building it. The talk covers the Mojito-based implementation of Axis, the “Reuse-Reduce-Replace” software philosophy, and the notions of optimization and adaptation in the context of Mojito!

Here is the recorded video:

Here are the slides:

]]>
http://caridy.name/2012/07/expanding-yahoo-axis-across-3-screens/feed/ 0
Webinar: “YUI Open Hours: Yahoo! Axis” (second half) http://caridy.name/2012/07/webinar-yui-open-hours-yahoo-axis-second-half/ http://caridy.name/2012/07/webinar-yui-open-hours-yahoo-axis-second-half/#comments Fri, 13 Jul 2012 00:59:39 +0000 caridy http://caridy.name/?p=274 As part of the second section about Axis, we focud on the mojito side. Here is the recorded session:


http://www.youtube.com/watch?v=1T5KMozs6Sc&hd=1

These are some of the bullets we covered during the second half:

Mojito (on Axis)

  • (caridy) mojito apps can be fully configured by the time your application logic executes; no logic branching within your app based on things like device, only configurations
  • (caridy) mojito context
  • (caridy) mojito YCB (show example of *.json)
  • (caridy) mojito dimensions
  • (caridy) mojito tunnel (executing an action, how it preserve the context)
  • (caridy) YUI Integration – Dependencies resolution (mention shaker and screwdriver)

That’s about it!

]]>
http://caridy.name/2012/07/webinar-yui-open-hours-yahoo-axis-second-half/feed/ 0
Webinar: “YUI Open Hours: Yahoo! Axis” (first half) http://caridy.name/2012/06/webinar-yui-open-hours-yahoo-axis-first-half/ http://caridy.name/2012/06/webinar-yui-open-hours-yahoo-axis-first-half/#comments Fri, 15 Jun 2012 20:56:19 +0000 caridy http://caridy.name/?p=263 Yesterday @ekashida and I did a quick walkthrough on the technical part of Yahoo! Axis, specifically the front end and the web components. Here is the recorded session:


http://www.youtube.com/watch?v=vIvFbJo1Fj8&hd=1

These are some of the bullets we covered during this first half:

Yahoo! axis architecture

  • (caridy) why native (performance, stability, etc)
  • (caridy) why web (reusable pieces, transparent updates, fine grained layouts using css, buckets, experimentation, etc)
  • (caridy) why hybrid (why BM is native, why SL is web, why Omni bar is native)
  • (keugene) why hybrid (how we mimic some of the native pieces for web)
  • (keugene) creating/destroying apps as needed to avoid memory leak issues altogether
  • (caridy / keugene) why independent apps and how it works

YUI Components used and extended in Yahoo! Axis

  • (keugene) [yui core infrastructure] extensions vs plugins (registration, race conditions, configs, etc)
  • (keugene) communication layer Y.CL overview (we show both perf analysis, and the post for postmessage vs Y.CL)
  • (caridy) smart localstorage (cache-offline-smart) and how we extend yui cache-offline for better performance and manageability
  • (keugene) [scrollview-hack] hooking into scrollview-paginator to implement our own anchoring process to avoid cutting cards
  • (keugene) [scrollview-hack] optimization
  • (caridy) [scrollview-hack] defining points of interest as new events (pulling)

Next week we plan to talk about “Mojito” in the context of Yahoo! Axis.

]]>
http://caridy.name/2012/06/webinar-yui-open-hours-yahoo-axis-first-half/feed/ 0
PostMessage performance analysis http://caridy.name/2012/06/postmessage-perf-analysis/ http://caridy.name/2012/06/postmessage-perf-analysis/#comments Wed, 13 Jun 2012 15:38:42 +0000 caridy http://caridy.name/?p=227 What is a postMessage?

window.postMessage is the de facto mechanism for enabling cross-origin communication at the browser level. In other words, it allows you to send a message (in the form of a string) from one document instance to another in a secure way. It exposes an API to send bi-directional messages between two windows, making this feature ideal for mash-up implementations where you can have two completely isolated documents (running on different domains) and still have a way to keep them in sync. All you need is a reference to the receiver window to post a message to it, e.g.:

receiverWindow.postMessage(message, targetOrigin);

Since the purpose of this post is to do a performance analysis, I will leave the basic introduction at that. Mozilla has an extensive description of postMessage [1], and since all major browsers already implement this feature using the same API, this should be enough to move on to the main topic.

What is a round trip postMessage and how does it work?

We can have a regular page that includes an iframe from a different domain, and we want to notify the iframe whenever a user interacts with the page so the iframe can execute some code and callback with the result of the operation. We are assuming the iframe doesn’t have any UI, but that’s not a requirement, we can do it backwards as well, where the user interacts with the iframe UI, and it has to notify the parent window about the interaction, and wait for some command. Both scenarios are valid, and perfectly doable with postMessage.

In the context of this analysis, we define a roundtrip message as a message that is sent from a parent document to a child document, and a response to that message sent from the child document to the parent document. Both documents belong to different domains and all messages are delivered via postMessage. The whole workflow works in an asynchronous way.

Why Y.CL?

Y.CL is a sugar layer on top of postMessage to facilitate the use of YUI Custom Events to wrap the low level implementation. On top of that, it facilitates the hand-shaking process between two windows to avoid any race conditions and queues messages until both sides are ready to receive them. We will be talking more about Y.CL very soon.

What are we testing here?

The purpose of the test [2] is to understand how fast browsers can deliver a message via postMessage, in a roundtrip fashion, and see how this technique is suitable for a NRT (near-realtime) implementation. The test is an echo-like roundtrip implementation where the parent document messages the child document with the string “marco” and the child document responds with the string “polo”.

Results

These are the results [3], specifically, the number of roundtrip messages that we can send per second:

Note: Although postMessage is faster than Y.CL, the difference is not significant. Considering the overhead of using YUI Custom Events and JSON.stringify(), it delivers a consistent and adequate abstraction for this functionality. Again, we will be talking more in details about Y.CL in the upcoming days.

Conclusions

window.postMessage is a mature feature, supported on all major browsers, including mobile browsers. It works pretty fast, and it is getting faster with every release. You should be able to send hundred of messages per second, and that should be good enough for the majority of the cases, including near-realtime applications.

In my opinion, it is better to isolate and maintain a consistent API through postMessage between two independent logical pieces in a complex application than trying to couple the two pieces into the same context. And postMessage could be really useful for creating mash-ups and decoupled web applications.

References

1. Mozilla Developer Network – window.postMessage API Doc

2. postMessage test suite on jsperf.com

3. Browserscope result page

]]>
http://caridy.name/2012/06/postmessage-perf-analysis/feed/ 0
What is Mojito? http://caridy.name/2012/04/what-is-mojito/ http://caridy.name/2012/04/what-is-mojito/#comments Mon, 02 Apr 2012 19:32:55 +0000 caridy http://caridy.name/?p=203

What is Mojito? Well, mojito is a traditional cuban drink, and since I’m originally from Cuba, I should know everything about it, and I do!, but today I want to talk about the other Mojito, the one from Yahoo!, the application framework, because today it was officially announced as the newest open source project.

My team and I have been using Mojito for quite some time, we were one of the early adopters within the company, and we used it to build a brand new product from scratch. So, I know a little bit about it, and I know you will have a lot of questions about it. Today, I just want to address general questions, but eventually I want to drill down on some of the topics.

Is Mojito a silver bullet for web applications?

There are not silver bullets in our industry. But IMHO, Mojito brings some new concepts to the table, and specifically it opens a new chapter for efficiency in the web.

How can Mojito help to create more efficient web applications?

Efficiency can be achieved when you have smart software that can react to runtime changes. In the context of web applications, and mobile web applications, the runtime depends on numerous vectors, some of them completely out of our control. For example, connection speed, battery life, traffic peaks, browser capabilities, device capabilities, etc. If the application can monitor each of those vectors, and react per user, per connection, per process, per routine, then you can achieve some mind blowing tricks to make your application really efficient, hence to make the web more efficient. Mojito has two unique features to empower you on this area.

  • Runtime context: which is a predefined set of dimensions/variables with a finite number of possibilities/values that will define the state of the execution at any given time.
  • Environment agnostic: the unique ability to run the same code in different runtimes. E.g.: browser, server, iOS UIWebView or any other phoneGap similar runtime.

When you combine these two features together, you can control how, when and where each piece of logic will be executed, so, you can define very simple rules to make your application to perform better under different circumstances per user, per request, per routine, etc.

What does “context” mean in Mojito?

In terms of JavaScript, a context is a literal object that contains a series of dimensions (properties, for example, region, device, connection speed, network, environment, memory, just to name a few), and each dimension can have a finite number of values. This literal object can be constructed on every request at the server side, or can be defined, redefined at the client side. This literal object will allow you to pick up certain pre-defined configuration that can be used to trigger and execute a certain piece of logic, or can be used just like a dynamic configuration hub for regular settings, language, etc.

This is a concept that we have been using for quite sometime at Yahoo!, but what is new in Mojito is that this context can now travel from server-to-client and vice versa, and can be modified at any given time, giving you full control over it.

Can I really execute the same code in the server and in the client?

Yes, you can. But it’s not magic. You have to define where you want to execute each piece of logic (javascript files) depending of the execution context following a very simple pattern to name your files, e.g.:

  • foo.client.js defines a piece of logic that is only available when running on the client side runtime.
  • bar.server.js defines a piece of logic that is only available when running on the server side runtime.
  • baz.common.js defines a piece of code that is runtime agnostic. In can run on either server or client side.

Now, if you have two pieces with the same name (e.g. foo.client.js and foo.server.js), Mojito will switch between logics automatically depending on the execution runtime. This allows you to tweak your logic easily. Keep in mind that *.client.js or *.server.js will be able to require any other piece of logic that could be client, server or common. This is a very powerful way to organize your code.

How does Mojito compare to other framework out there?

I have used and tried many other Node.JS frameworks in the last two years or so, and all of them (no exceptions) suffer from the same problem, separation between server and client. I think Mojito does a pretty good job blurring that separation, and as a result, you will notice an increase on productivity from the development point of view.

Was Mojito built from scratch in Node.JS?

No. Mojito was built on top of two well known/tested frameworks:

  • YUI Library: which is the foundation of the javascript module structure and the basic abstraction for most of the JavaScript pieces in Mojito. You don’t need to know YUI to use Mojito though, Mojito obscures most of the YUI features, and you can use JavaScript or any other JavaScript library if you want (if it can run in the server side just like YUI does it).
  • Express: “High performance, high class web development for Node.js“ as the underlaying serving platform for the server side.

They are both open source projects.

How hard is to get up to speed on Mojito?

To be honest, it will be hard. You need to be able to reach some level of abstraction to really embrace the Mojito paradigm, but also to be able to squeeze every bit of it. It takes time to understand how it works, and how to tweak it, but it is worth the effort. Especially for those who know YUI, it will be easier to adapt to Mojito.

Which types of web applications are more suitable for Mojito?

Most web applications that are meant to be used in different devices can probably fit into Mojito paradigm. But those that are set to scale in terms of traffic and performance are more suitable for it IMHO.

What kind of cool stuff can I do with Mojito?

As @rw0 mentioned in his post, you can create an application that can easily instrument the latency and response time of every network activity within the app, and translate that in changes in a dimension within the context. Let’s say we have a dimension like this:

{ speed: { fast: null, regular: null, slow: null, shitty: null } }

Based on the instrumentation, you can adjust the value of “speed” overtime. If the user is using an iPhone, connected to a wifi network, and suddenly s/he step out of the room, switching to a shitty 3G connection, and if we can detect that change, and re-asset the “speed” dimension, that means we can easily change the way we serve traffic/content for the user. Maybe we can now make a single request bundling content, assets, data into a single response (JSON), putting some pressure on our servers (which will do the bundling process) for that particular user in order to keep s/he running without a degradation of the service.

What else can I do with it?

Based on the previous example, what if we instrument our servers to detect changes in the level of CPU or memory usage?, and depending on a dimension, we can delegate some bundling, rendering, and fetching processes to our client’s runtime in an event of a traffic peak, instead of just degrading the service, or serving stale content just to avoid an outage. And this is only possible because of JavaScript, and the ability to run it in the server or client based on the execution context. I think this is a killer feature.

Where can I host a Mojito application?

A Mojito application is just a Node.JS application. Ideally, if it is set to scale, you should try to find an elastic cloud (maybe Amazon EC2) to host it. Internally, we use Yahoo! Manhattan Cloud, which is another piece of the Yahoo! Cocktails platform, and hopefully you will be able to use it too soon. Ask @olympum for more details hehehehe!

Where can I download the source code?

Mojito source code is hosted in github.com/yahoo/mojito, go and get it. We hope you can fork it and help us make it better by submitting patches and new features.

How can I use it?

Check the quickstart section from the official page.

That’s all for now, feel free to ask/comment!

Here are some others links to get you running on Mojito:

]]>
http://caridy.name/2012/04/what-is-mojito/feed/ 2
Getting up to speed with YUI 3 http://caridy.name/2009/11/getting-up-to-speed-with-yui-3/ http://caridy.name/2009/11/getting-up-to-speed-with-yui-3/#comments Mon, 16 Nov 2009 22:56:26 +0000 caridy http://caridy.name/?p=175 Few folks asked me about YUI 3 and how they can get up to speed with this new version of Yahoo! User Interface Library. Well, here is a quick guide to get up to speed in 3 days. Yes you heard me right, only 3 days, assuming you already know JavaScript and YUI 2. ;-)

First block (day one) – General Architecture

In the first day, you will have to expend around 4 hours watching videos, getting a lot of information. There is not time to tackle this little by little, hahahaha. It’s better to get the whole insight in a row.

(Day 1, Task 1). General Concepts

Let’s start with a general talk by Nicholas. He really explores some of the basic design principles used to build YUI 3. He didn’t mention YUI 3, but I believe if you understand these general concepts, will be easy for you to understand YUI 3.

Nicholas C. Zakas — Scalable JavaScript Application Architecture
Frontend architecture for complex, modular web applications with significant JavaScript elements.
http://developer.yahoo.com/yui/theater/video.php?v=zakas-architecture

Then you can jump for the real stuff. These 3 videos were recorded during YUI Conf 2009, and are essential in the process of understanding the underlying concepts behind YUI 3.

(Day 1, Task 2). YUI Infrastructure

Eric Miraglia — Welcome to YUI 3
YUI engineer Eric Miraglia provides a high-level introduction to key concepts underlying the YUI 3 codeline.
http://developer.yahoo.com/yui/theater/video.php?v=miraglia-yuiconf2009-yui3

(Day 1, Task 3). Events Infrastructure

Luke Smith — Events Evolved
YUI engineer Luke Smith provides a deep introduction to the YUI 3 event system including its support for DOM events, event delegation, synthetic events, and custom events.
http://developer.yahoo.com/yui/theater/video.php?v=smith-yuiconf2009-events

(Day 1, Task 4). Widget Infrastructure

Satyen Desai — A Widget Walkthrough
YUI engineer Satyen Desai provides a detailed tour of the YUI 3 widget subsystem. (Slides).
http://developer.yahoo.com/yui/theater/video.php?v=desai-yuiconf2009-widgets

Second Block (day two) – Experimenting

In this second block you will be able to get some insight, checking some real examples, and getting some feeling about the new code style and the new infrastructure.

(Day 2, Task 1). Playing with the Official Examples

You should spend some time checking some of these examples. Keep in mind that for every example in the library we have a page with the full explanation, this can help you to understand better how things work. Here is an example, and has you can see, there is a link to display the working example in a new page, or you can see it within the iframe and the description is below that.

YUI 3: Index of Examples
YUI 3 ships with a series of 130 examples that illustrate the implementation of its components. The examples can be starting points for your exploration, code snippets to jump-start your own programming, or simply inspiration as to how various interaction patterns can be enabled in the web browser via YUI.
http://developer.yahoo.com/yui/3/examples/

(Day 2, Task 2). Checking the state of the library

It’s important to understand the state of the library, the list of available modules, and the state of each module. Keep in mind that every module contains a landing page with some information (the most important), but there are some more pages and the API Docs with tons of valuable info. Don’t spend too much time digging from here, it’s better to explore each component when needed, having a real use-case in mind.

http://developer.yahoo.com/yui/3/

Try to focus on “Core” and “Component Infrastructure” sections. Also, spend some time reviewing the dependency configurator tool, it will give you some feeling about the granularity and the organization.
http://developer.yahoo.com/yui/3/configurator/

(Day 2, Task 3). Debugging

Now that you have nailed down some of the general concepts, and you will start checking some examples and putting some examples on your own, it’s important to know how the debug your code. YUI 3 offers a variety of tools and utilities to help you during the development process:

Luke Smith — Debugging in YUI 3
YUI engineer Luke Smith discusses the fine art of debugging web applications, looking at general tools and techniques and providing a few specific hints about debugging in YUI 3.
http://developer.yahoo.com/yui/theater/video.php?v=smith-yuiconf2009-debugging

(Day 2, Task 4). Performance Implications

With YUI 3 we are trying to beat all the barriers in terms of performance. Normally is not recommended to introduce performance optimization in the early stages for a project, it’s important to know the general concepts behind YUI 3 Loading process, and how to leverage YUI 3 infrastructure to create hight performance web applications.

Matt Sweeney — YUI 3 Performance
YUI architect Matt Sweeney reviews principles of high-performance web development and looks at how best to implement those principles in YUI 3-based projects.
http://developer.yahoo.com/yui/theater/video.php?v=sweeney-yuiconf2009-performance

After that, you should be able to continue with the library documentation and the examples.

Third Block (day three) – Extending and Contributing

(Day 3, Task 1). Creating your own modules

Caridy Patino – Building YUI 3 Custom Modules
Learn how to leverage the YUI 3.x infrastructure to create custom code that can be loaded easily and efficiently onto any page. Also discover how these mashups can combine YUI widgets and utilities with your own code and how to reuse code between different YUI instances.
http://www.slideshare.net/caridy/building-yui-3-custom-modules

(Day 3, Task 2). A real world use-case

In every project, is always good to get a different angle, a different perspective, and outsider insight:

Eric Ferraiuolo — Web App Development with YUI 3
Eric Ferraiuolo of Oddnut Software talks about the nuances of deploying real-world web applications using YUI 3.
http://developer.yahoo.com/yui/theater/video.php?v=ericf-yuiconf2009-webapps

(Day 3, Task 3). How to contributing to YUI

If you’re really into YUI, you should take the time to check this awesome video from Dav Glass:

Dav Glass — Contributing to YUI
YUI engineer Dav Glass introduces you to the YUI Gallery and steps through the process of making contributions to the YUI project.
http://developer.yahoo.com/yui/theater/video.php?v=glass-yuiconf2009-contributing

Check the YUI 3 gallery here:
http://yuilibrary.com/gallery/

Few more thoughts

There is a bunch of videos in the YUI Theater, make sure that you check them, some of them are really useful, other are very technical or diving into an specific subject. Also, there are a bunch of them explaining in details some of the tools created by YUI Team as well.
http://developer.yahoo.com/yui/theater/

YUI Blog is another good reason to keep you updated about the library. Including some good articles (again, some technical deep dive).
http://www.yuiblog.com/

And finally, you can join us thru the community. This site, with such a great organization, provides multiple ways to get in contact with YUI Core Team, YUI Contributors and the community in general.
http://yuilibrary.com/

]]>
http://caridy.name/2009/11/getting-up-to-speed-with-yui-3/feed/ 6
Bootstrap using “YUI Loader” and “YUI Get Utility” http://caridy.name/2009/05/bootstrap-using-yui-loader-and-yui-get-utility/ http://caridy.name/2009/05/bootstrap-using-yui-loader-and-yui-get-utility/#comments Thu, 07 May 2009 22:25:24 +0000 caridy http://caridy.name/?p=149 Everyday more and more developers use on-demand loading to improve performance and round “trip” times for web applications and even for traditional web pages that require a certain amount of JavaScript code.

In YUI 2.x, we have two components that can help us to define on-demand rules. These are the YUI Get Utility, and the YUI Loader.

YUI 3.x is a different story, this new version is based on the on-demand philosophy, and because of that, Loader and Get Utility are part of YUI Core.

About this article:

In this article, I will focus on YUI 2.x and specifically, how you can design your application to use the YUI on-demand capabilities in such a way that the transition to YUI 3.x will be straightforward. The main goal is to describe how we can use YUI to organize the code and learn how to deal with on-demand loading processes rather than focus on performance improvements. If you are looking for a performance boost, certainly this technique can help, but I will recommend you to follow the links provided at the bottom of this article.

From my point of view, there are two different types of web applications or pages:

  • Monolithic Applications:
    The application and all its features/behaviors are controlled by a single object/script. Modifications in the application usually impact the core and the application in general.
  • Granular Applications:
    The application is based on regions/webparts that represent certain areas. Usually some of these regions/webparts can be switched or removed from the application without impacting the rest of the functionalities.

I believe the second option (granular applications) is the way to go, especially for more complex applications. Also, this option will most likely make use of on-demand loading, where each region/webpart should be able to load its requirements and execute its own initialization process when it’s requirements become active and it’s DOM structure becomes available in the DOM.

Note: regions/webparts are atomic units used to build each page. Usually they are represented in the DOM as a simple DIV, and are contained as a granular part in the application. From now on, I will refer to these elements as “regions”.

That said, lets see a couple of diagrams to analyze what is the gain behind the on-demand loading process. These are manually created diagrams representing the loading and execution process for a page.

Application timeline:

These two diagrams represent a page/app in which, for the sake of example, contain only two regions (left-column-renderer and ad-renderer).

Traditional process: inserting tags within default DOM structure of every page.

Default Browser Loader: Loading and Execution Timeline

Default Browser Loader: Loading and Execution Timeline

Notes for this diagram:

  • it represents a generic app timeline for a simple page with a bunch of script tags.
  • the scripts can be at the top (in the head) or at the bottom of the page (before </body>), and the sequence is more or less the same.
  • yui-modules” represent a set of YUI modules (probably using YUI Combo Handler to include them all using a single call.
  • bubbling” is a 3rd party module that cannot be loaded thru the YUI Combo Handler.
  • “swf-object” is a well-known 3rd party component to handle flash movies, and it represents another requirement.
  • …other…” represents other regions in the application.

On-demand loading process: using YUI Loader to load the requirements and YUI Get Utility to execute the initialization processes for each region.

Loading and Execution Timeline

YUI Loader and Get Utility: Loading and Execution Timeline

Notes for this diagram:

  • we use some of the elements described in the previous one.
  • “yui-loader” is a small file (only 9.4KB) and it packages Yahoo Global Object, Get Utility, and YUI Loader engine.
  • “boot” is usually a tiny file with the application logic, the definition of the 3rd party modules (swf-object and bubbling), and the list of other dependencies (initializers and renderers) that should be loaded thru YUI Get Utility (like left-column-renderer, ad-renderer, etc).
  • items at the same level can be executed at the same time (JavaScript is a single execution thread, and so, the first to become ready will be the first to be executed).
  • swf-object was transformed into a YUI Module to fit this example (it can be also be treated as a component if you want to).
  • items in the 3rd block (left-column-renderer, ad-renderer, etc) will be included dynamically by the bootstrap definition.

Lets try to identify differences between these two approaches:

The first difference that you may notice in these two diagrams is the “domready” event. It will be more likely to arrive first in the second approach because those scripts will be injected on-demand without blocking the loading process. It could arrive even before the “bootstrap ready” mark, depending on the complexity (size) of the DOM structure.

In theory, the bootstrap is responsible in defining what should be loaded and executed after the “bootstrap ready” moment occurs. This means that we can control everything at the JS level instead of depending on the default DOM structure. So all the logic will be at the JS layer and we should be able to delay certain initialization processes, or switch between them based on the user preferences, etc. All this granularity will be handled at the JS level.

Lets see some code:

Entry Point (index.html):

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
 "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
    <title>Bootstrapping for a Web App using YUI 2.x</title>
    <script type="text/javascript" src="bootstrap.js"></script>
</head>
<body class="yui-skin-sam">
	<p>Web App.</p>
	<div id="mod-left-column">
	  ...
	</div>
	<div id="mod-content">
	  ...
	</div>
	<div id="mod-ads">
	  ...
	</div>
</body>
</html>

Bootstrap script (bootstrap.js):

/*
 * Encapsulation Pattern: Conjuring YUI from thin air (by Chris Heilmann)
 * http://www.wait-till-i.com/2008/08/02/conjuring-yui-from-thin-air/
 */
YAHOO_config = function() {
    /* injecting the YUI Loader in the current page */
    var s = document.createElement('script');
    s.setAttribute('type', 'text/javascript');
    s.setAttribute('src',
        'http://yui.yahooapis.com/2.7.0/build/yuiloader/yuiloader-min.js');
    document.getElementsByTagName('head')[0].appendChild(s);
    return {
        // true if the library should be dynamically loaded after window.onload.
        injecting: true,
        listener: function(o) {
            // waiting for the loader component
            if (o.name === 'get') {
                window.setTimeout(YAHOO_config.ready, 1);
            }
        },
        ready: function() {
            var loader = new YAHOO.util.YUILoader();
            // defining custom modules
            loader.addModule({
                name: 'bubbling',
                type: 'js',
                fullpath: 'bubbling/bubbling.js',
                requires: ['yahoo', 'event', 'dom']
            });
            loader.addModule({
                name: 'swfobject',
                type: 'js',
                fullpath: 'tools/swf-object.js'
            });
            loader.require(['bubbling', 'swfobject']);
            loader.combine = true;
            loader.insert({
                onSuccess: function() {
                    /* initializers and renderers here */
                    YAHOO.util.Get.script([
                        "left-column-renderer.js", "ad-renderer.js"
                    ], {
                        onSuccess: function() {
                            /* we are ready to roll, now we can
                               do more initializations here */
                        }
                    });
                    /* more initializations here, if
                       you don't want to use Get Utility */
                }
            });
        }
    };
} ();

The developer should define the generic structure for the application within the bootstrap, specifying the requirements, components, and modules for the application. So, basically, the bootstrap would be different for each site, application (or even for page).

Identify what should be loaded using YUI Loader or YUI Get Utility:

The difference between the modules and components/initializers/renderers is that modules are structures based on YUI, with the corresponding registration process, and the components are simple JS files.

All YUI components/utilities/widgets (modules) should be loaded thru the YUI Loader (along with 3rd party modules), and will be loaded on the page once.

YUI Get Utility should load scripts that implement a certain initialization/renderer process for a region in your application, or some kind of delayed routine to enhance the page.

Initialization and renderer processes:

Loader’s “onSuccess” is the first stop in the loading process (“bootstrap ready” in the diagram). At this point we can decide if we want to put all the initialization process within that function, or if we want to load some JavaScript files, and they will carry on with the initialization process for each different region in the page, getting some granularity for each page.

The initialization/renderer process should wait until the DOM structure that represent the region that we want to enhance gets available (onAvailable or onContentReady). If we want to extend/expand that DOM structure, just wait until DOM gets ready (onDOMReady) to avoid malfunctions in IE. Here is an example:

Left Column Renderer (mod-left-column.js):

YAHOO.util.Event.onAvailable('mod-left-column', function (el) {
  /* initialization process here */
});

In this case, we should include all the requirements before this block is executed.

In YUI 3.x, things are a lot easier. For example:

YUI({}).use('node', 'json', 'io', function(Y) {
  var node = Y.get('#mod-left-column');
  /* initialization process here */
});

Instead of including all the necessary requirements (modules) at the bootstrap level, YUI 3.x Loader will do it automatically during each region’s initialization process

Real examples:

Final notes:

  • The loader object can be used at any time, even during a region initialization part. It’s a good practice in YUI 2.x to have a single reference for the loader. With small changes in the code, we can easily share and re-use the “loader” object thru “YAHOO_config.loader“, across the application.
  • CSS files can be loaded thru YUI Loader or YUI Get Utility in the same way as JavaScript files.
  • For production, it’s a good practice to minimize the number of request (JavaScript files). In this case you can combine all the 3rd party modules in a single file, and even combine all the components/initializers/renderers in a single file.
  • Using inline JavaScript blocks to initialize some of the regions is not a good option; they block the rendering of everything in the page.

More Information:

There are a lot of good articles about on-demand loading and how it helps to improve the performance, as well as its implications. Here are some of them:

]]>
http://caridy.name/2009/05/bootstrap-using-yui-loader-and-yui-get-utility/feed/ 6