Altabel Group's Blog

Posts Tagged ‘JavaScript

Almost everyone involved in web development knows jQuery or at least heard of it. Being simple and concise, it makes web developers’ life much simpler. But could it be a solution to every problem? Unfortunately not.  Once you decided to create more complex web apps, you are to face a problem, as there is no easy way to make your UI and data communicate with each other dynamically. And you need a library which will provide you with a more sophisticated way of communication between your UI and the underlying data model. And here is where Knockout (KO) could help.

What is Knockout?
Knockout is a JavaScript library which helps to create rich, desktop-like web UIs. It was developed and is maintained by Steve Sanderson, a Microsoft employee. KO simplifies user interactions and makes interfaces fully responsive to any data source changes. It provides a simple two-way binding mechanism to link a data model to an UI, thus making synchronization between them very easy.

 Pros:

-     Dependency Tracking
 The right parts of your UI are automatically updated whenever your data model changes. This is achieved by the two way bindings and a special type of variables called observables. You don’t have to worry about adding event handlers and listeners for dependency tracking.

-     Declarative Bindings
 This allows you to bind the elements of UI to the data model in a simple and convenient way. When you use JavaScript to manipulate DOM, this may cause broken code if you later change the DOM hierarchy or element IDs. But with declarative bindings even if you change the DOM – then all bound elements stay connected. You can bind data to a DOM by simply including a data-bind attribute to any DOM element.

-     Templating
 This becomes useful when your application becomes more complex and you need a way to display a rich structure of view model data, thus keeping your code simple. Knockout can use alternative template engines for its template binding. It has a native, built-in template engine which can be used right away.

-     Compatibility and Extensibility
 Knockout is compatible with any back-end technology and on the front-end it does as much or as little as you decide. It leaves many decisions to you to make, thus letting pick the best tool to meet your specific needs. Knockout doesn’t care about how you communicate with the server or how you choose to do routing, but there are several third party libraries that do a fine job of these things (like sammy.js for routing and upshot.js for data-access). It goes without mentioning that it works fine next to jQuery. Knockout is also easily extensible. To modify or extend the default functionality, it offers features like custom bindings, and custom functions. There are also several plugins already written for KO.

-     Ease of Learning and Use
 The documentation for knockout is probably the best have ever been seen. It has an amazing interactive tutorial system, live examples, and the documentation is extremely comprehensive and easy to understand. For most developers already familiar with JavaScript it should not take more than a few days to pick it up and start using.

Some additional benefits are the following:
•          KO is a pure JavaScript library – so it works with any server or client-side technology
•          It can be added on top of your existing web application without requiring major architectural changes
•          It’s compact – around 13kb after gzipping
•          It works on any mainstream browser (IE 6+, Firefox 2+, Chrome, Safari, others)
•          Comprehensive suite of specifications (developed BDD-style) means its correct functioning can easily be verified on new browsers and platforms

Cons
 -              All JavaScript variables and arrays are functions (also known as KO observables) as opposed to Angular. This can be a little confusing at first for some people. But it should be noted that all native JavaScript array functions like splice(), indexOf(), push() etc. are implemented by Knockout and may be used on KO observables.
-              HTML views can get messy as declarative bindings increase. This can be weakened to some extent through the use of custom bindings, computed observables and by attaching events to the DOM using jQuery instead of using the data-bind attribute.
-              Additional functionality like data-access and url-routing are not included. If you are looking for an end to end solution that offers a complete toolbox of common web-app functionality, you should probably check out such frameworks as Angular or Ember.

Knockout VS jQuery

Knockout.js is not a replacement of jQuery (as well as of Prototype, or MooTools). It doesn’t attempt to provide animation, generic event handling, or AJAX functionality (however, Knockout.js can parse the data received from an AJAX call). Knockout.js is focused only on designing scalable and data-driven UI.

Moreover Knockout.js is compatible with any other client-side and server-side technology. It also acts as a supplement to the other web technologies like jQuery and MooTools.

Although you will need to use Knockout with jQuery at the same time, in some cases like animated transitions, Knockout itself doesn’t depend on it. Another thing you need to understand is that Knockout doesn’t compete with jQuery – they both do excellent job; each one in its own direction. And if you want to get the most benefits you should use them together.

Knockout is the simplest of all the frameworks as well as one of the smallest. It does not claim to be able to solve all your problems, but it does claim to do a few useful things and do it better than the alternatives. In the words of Knockout creator Steve Sanderson, it is “low risk” because its uses are focused and it is compatible with any other technologies you are using and you can use it in a very small part of your application or your entire application. For someone who wants to take their project to the next level without too much risk, knockout is a great choice.

Hope you found the information in this article useful. Your valuable feedback, question, or comments about this article are always welcome! :)

Yuliya Tolkach

Yuliya Tolkach
Yulia.Tolkach@altabel.com
Skype ID: yuliya_tolkach
Business Development Manager (LI page)
Altabel Group – Professional Software Development

There is no doubt that mobile industry is one of the most intensely growing nowadays. Any product that earlier used to be desktop or web is moving towards going mobile. Everyone is taking designing experiences for smaller screens seriously. As for the web, we’re seeing swarms of recently updated sites that are employing responsive design or more mobile-friendly layouts. This is quite critical, especially when you consider that accessing the web from mobile devices is on track to surpass desktop usage in a just a year or two.

With so many mobile apps/sites out there you have to do all it takes to deliver a good mobile product that will be competitive on the market. The key input for success here often is conditioned by the convenience of mobile services. You have to start predicting what the customer wants to see when they try a mobile application or website. The use of mobile context in delivering mobile experience is just one of the big challenges that application developers face. Here’s a number of the most important challenges we see.

1. Mobile Context

There has always been emphasis on context – the idea of being sensitive to where users might be and what they might be doing at the same time that they’re using your app/site. Is a user in line at the grocery store or on the living-room couch? Is a user connected to the Internet via Wi-Fi access, with fast page loads, or an infuriatingly weak Internet connection? Are both of the user’s hands holding the device in landscape orientation, or is the user using only the right thumb to navigate the interface in portrait mode? We have to think about all of this. Basically the customer’s mobile context consists of:

Preferences: the history and personal decisions the customer has shared with you or with social networks.
Situation: the current location, of course, but other relevant factors could include the altitude, environmental conditions and even speed the customer is experiencing.
Attitude: the feelings or emotions implied by the customer’s actions and logistics.

Getting a good contextual awareness will require collecting information from many sources. For instance it could be mobile device itself, the local context of devices and sensors around them an extended network of things they care about and the historical context of their preferences. Gathering this data is a major challenge because it will be stored on multiple systems of record to which your app will need to connect.

2. Device Proliferation

Another challenge facing mobile developers is device proliferation. It looked like mobile app development process was pretty well defined: build your app, make sure it looks pretty on a 4-inch smartphone and a 10-inch tablet, then submit it to an app store. Most app developers prioritized a few popular devices, such as the iPhone, the Samsung Galaxy S III and the iPad.

It’s not quite that easy now, and it’ll be much tougher in the near future. Picking the most popular devices will become more of a challenge as device types and platforms proliferate. Google and Apple already support tablets of different sizes and, with Windows 8 now shipping, developers can expect to find a whole range of larger touch-sensitive devices, such as Hewlett-Packard’s Envy series.

3. Voice rather than Touch

There are a lot of situations where you would want to build voice input into your app today. For a running or fitness app, a phone is likely to be strapped to a person’s sweaty arm. The same is true while driving. Modern applications are to let people use their devices while keeping their eyes and hands off it.

4. Hybrid Applications

With each release, popular mobile operating systems get better at supporting HTML5 and its attendant APIs. That capability will let companies reuse more code across multiple devices, which will be important in keeping app development costs down taking into account the proliferation of connected devices and form factors.

As a result we could expect that more companies will turn to web technologies with a centralized code base for core components of their connected applications. That centralized code is likely to be a combination of HTML, JavaScript and CSS, because the vast majority of devices will support it. Much of this HTML5 will be delivered as hybrid apps, which mix HTML code into a native container and use native code for navigation and platform specific integration. These hybrid apps will get more sophisticated and capable as a result. We’re already seeing compelling enterprise applications built with the hybrid approach.

5. Cloud Powered Mobile Applications

With the power of the cloud, the mobile application market is about to change radically. Several industry analysts predict that mobile applications will gradually move to the cloud and move away from being installed and run directly from the handsets themselves. Instead, cloud powered mobile applications are accessed and executed directly from the cloud through a mobile web browser interface and several technologies facilitating this change are already available. HTML5, for example, is necessary for enabling caching on the handset, so that users will experience uninterrupted service levels despite fluctuations in network service delivery.

Cloud powered mobile applications are not limiting their choice to one platform. Application developers also have real advantages from mobile cloud computing. The largest benefit is that it allows them to have access to a larger market. This means developers will have a much wider market which means they can bypass the restrictions created by mobile operating systems. But with greater developers’ power comes greater responsibility for security and performance. Expect more developers to be on call for application support in the new model, using triage to handle defects and investigate degradation to production services. Those tasks have traditional been the domain of systems administrators. Expect IT operations personnel to become integrated into development teams and to start their work at the inception of an idea.

I think the challenges mentioned are some of the most important ones. What are the challenges you have already faced in the mobile development? Even more interesting to hear about the challenges you are envisaging for the near future! As usual many thanks for sharing your thoughts!

Aliona Kavalevich

Aliona Kavalevich
Aliona.Kavalevich@altabel.com
Skype ID: aliona_kavalevich
Business Development Manager (LI page)
Altabel Group – Professional Software Development

Responsive web design isn’t the future, it’s the present

In our humble opinion it’s late to debate whether responsive web design is the future because it’s already the present of everybody’s business represented online. Consumer/client behavior has been changing. According to statistics and analysts’ predictions, for instance, for the first time since 2001, PC sales are projected to be lower than they were in 2012; smartphone sales will double PC sales in 2014; tablet sales are expected to exceed 100 million this year and may top notebooks next year. So the shift to mobile is happening at an extraordinary speed, and tablets and smartphones are becoming extremely popular for business and pleasure matters. This means people view your content on thousands of oddly shaped and different sized screens. What’s more, according to Google research, mobile users “expect their mobile experience to be as good as their desktop experience” – this expectation poses a thorny challenge for both, business stakeholders and web designers and developers.

So this is no longer about “How do I make my website available to a smartphone or tablet?” – it’s “How do I make my business available in smartphone and tablet context?”. For some business it’s not important – it’s literally critical, for example: according to the Pew Research Center, 60% of tablet users prefer reading news on the mobile web than via an app; the same percentage is quite common for e-commerce sites according to Google Analytics and that’s why RWD has been listed in E-commerce marketing checklist for 2013. If you wish to identify the percentage of your audience that use mobile devices use the Google Analytics Mobile Overview report feature: if mobile users are more than 5% of your total audience you should consider catering for them too.

In general, there are three main approaches to providing information and interaction to mobile/tablet device users : responsive (and adaptive) web design, mobilized websites, and mobile apps. It’s important to understand that these are different marketing channels and their value proposition is very different. A mobile web site may do something very different from a mobile app – simply said, “if your goal is just to display and show content beautifully create a responsive or mobilized website; if your goal is to show productivity tools, build an app”. Which option is the best for your business will depend on your use case, your users’ habits and your budget.

Responsive web design vs mobile web development: advantages and challenges

To talk about advantages of responsive web design, let’s start from its definition. RWD is a front-end development approach aimed at crafting device agnostic sites. It uses “media queries” to figure out what resolution of device it’s being served on. Flexible images and fluid grids then size correctly to fit the screen. So responsive design provides easy reading and navigation with a minimum of resizing, panning, and scrolling, and eliminates the need for separate sites for different devices. Adaptive web design is either a subset of responsive design, or a related approach. “Responsive design will show more stuff or less, optimized for a mobile layout, but is likely to still provide access to the full desktop-view’s content. Adaptive design, by contrast, might show very different content, and also present a different UI, reflecting touchscreen’s tap/swipe/scroll versus desktop’s keyboard/mouse interaction.” In either case, responsive (and adaptive) web design will be based on the same code as a desktop site, and will locate on the same URL.

- In the definition above a couple of advantages of RWD are pointed out. Indeed, it improves user web browsing experience since a website adapts to the browser or device compatibility automatically and makes the content look good. For customers it shows that your business is receptive to changing technology and understanding of consumers’ needs.

- From business perspective, “one website – multiple devices” concept means that it’s easy to manage and focus on developing good content for your website. The same applies to analytics and strategy development and deployment since there is only one set of analytics to examine and a single strategy to develop and deploy. From maintenance standpoint, the technique is great too as one update affects all of your platforms.

- Additionally, responsive websites are easier for consumers to find than traditional or mobile web sites because they come up higher in search engines’ rankings. “In fact, Google recommends responsive web design because having a single URL for desktop and mobile sites makes it easier for Google to discover content and for Google’s algorithms to assign indexing properties to content.”

- One more advantage from the future perspective, as Resnick predicts, is: “As the internet transforms further into a platform of services and user interfaces that tie those services together, leveraging RWD technology in the future will allow companies to integrate a plethora of back-end services, such as Facebook, Twitter, Salesforce.com, and Amazon Web Services, and then present the integrated data back out the front-end iad layer on a responsive design so the application looks great on all devices without custom coding needed for each device or screen size. No longer are expensive back-end solutions needed to integrate legacy systems with business partners.”

Actually responsive web design is quite immature so it faces many challenges too.

- Even though we might view a responsive website on a smaller screen and it displays less visible content or smaller-sized images, this does not mean that the site will load faster. The thing is that from one side responsive websites are not much smaller in download size when viewed on smaller devices or screen resolutions compared to when being viewed on a desktop browser jacked into a broadband internet service provider, on the other hand mobile internet speeds still lag much behind broadband internet ones. Thus responsive web sites need advanced optimization, such as serving smaller images and conditionally loading scripts, and much more. An alternative may be found in dedicated mobile web development solutions since they specifically address mobile devices.

- The related issue concerns complexity. Responsive web designs are inherently complex because they are trying to support many viewing experiences without necessarily optimizing the experience for one particular device (or genre of devices). Mobile browsers will have to deal with a big HTML file, and the site would need to carefully avoid running specific scripts, loading certain CSS and download large images. Perfect implementation is possible, still avoiding over-resourcing requires scripts or code and therefore additional complexity. Typical “m dot” site wins in this case and is simple. It usually has a small amount of HTML, limited scripts, CSS, and images (if at all) as it is built specifically for its intended small-screen, touchscreen mobile devices viewing experience.

- As for UI and UX, responsive websites have limitations here. Not only in screen size, they are also limited for utilizing or recognizing key mobile features such as user location, connectivity, device limitations, software potential, and user needs. Mobilized sites and mobile apps will provide broader opportunities and advantages here.

- Information architecture can be an issue. It needs to be carefully considered and should be hierarchically structured before the design implementation.

- Advertising is an issue. Ads will have to shift with the sites, something that will wreak havoc with advertisers who want guaranteed placements on sites.

So, which approach will or do you use to present your business online?

HTML5’s momentum and Best tools for responsive web design

Responsive web design is not a specific technology but a whole design approach. However, responsive design is enabled primarily by CSS3 and JavaScript, which fall under the banner of HTML5. HTML5 is really maturing in terms of its functionality and, more importantly, its speed. So now HTML5 is the backbone of the new and interactive features of responsive web design.

To achieve a smooth flow from a large screen to a small one it takes a lot of patience and perseverance. To reach a seamless result there are a number of tools that help you with it. Below you will find a list of best responsive design tools broadly recommended in the web as well as by Altabel’s dev team:

1. Gridset
A tool that helps you design, prototype and build any type of grid layout required – columnar grids, asymmetrical, fixed, fluid or responsive grids. It even lets you create a library of your own grids, with a variety of presets available. It will allow you to build responsive prototypes (without all the calculations) very quickly and easily, providing all the measurements and tools to integrate with your existing markup.
Alternatives: Frameless, Tiny Fluid Grid, Gridpak, SimpleGrid, Responsify, Responsive.gs, Golden Grid System and Photoshop Grid for Responsive Design.

2. Bootstrap
An intuitive and powerful front-end framework from Twitter to start a responsive website fast and easy. It addresses the most popular user interface components and interactions, uses a 12-column responsive grid system with simple and flexible HTML, CSS, and Javascript and features dozens of components, styles and JavaScript plug-ins, with basic global display, typography and link styles all set. It also gives the option of customizing components of your website for instance by using the Customizer .
Alternatives: Skeleton, Foundation, Base, InuitCSS, LESS Framework, Gridless, 320 and Upand Gumby.

3. Wirefy
Clients wish to see how wireframes will adapt to different device sizes. Static wireframes aren’t particularly useful to show a client how responsive your design is, or what functionality is being suggested. But rapid prototyping by building flexible wireframes may. Wirefy is a collection of functional responsive HTML snippets and templates that scale as the browser is resized (working across multiple devices). It builds on tools such as the Frameless grid system and Bootstrap, and uses CSS media queries that adapt to different device resolutions. Wirefy focuses on key elements such as typography, tables, images, slideshow, forms, tab panel, paginator, menu, etc., focusing on the users.
Alternatives: Froont, Interactive Style Tiles, Responsive Sketch Sheets, Responsive Wireframe Template, Interface Sketch Templates, Responsive Device Diagrams, Wirify.

4. FlevNav
Navigation strategy is a really critical component of any responsive website design. FlexNav is a jQuery plugin that takes a device-agnostic approach to complex site navigation. It is a mobile-first concept using media queries and JavaScript to create a menu with drop downs. It features multiple nested sub-menus, with support for em units and tap targets to reveal sub-menus for touchscreens.
Alternatives: TinyNav.js, Navigation Patterns for Responsive Design, MeanMenu, Responsive Solutions for Menu Navigation, jPanelMenu.

5. Adaptive Images
Previously, making your website images responsive was tricky and usually meant using a “hack-around”. Now several tools may simplify this task. Using a one htaccess file, one php file and a single line of JavaScript, Adaptive Images detects screen size of browsing devices, cashes and delivers device appropriate re-scaled versions of your web page’s embedded HTML images without any mark-up changes. Also it is entirely non-destructive, and works on existing websites and markups — without the need to edit anything. Adaptive Images works on the premise that you are already using the highest-resolution images on your site, and also offers a ton of customization options.
Alternatives: ReSRC.it, jQuery Picture, ResponsiveImg, Retina.js and Retina Images.

6. FitText
As content scales according to a user’s viewport, the text will naturally wrap as the container is narrowed; and this often causes widows, orphans or your headlines to look rather ugly, and can even break the entire layout. FitText is a jQuery plugin specifically for headlines and big text. It auto-updates the font size according to the width of the element wrapping it, so you can achieve scalable headlines and a non-broken layout that can be caused by font-sizing issues. FitText works perfectly with Lettering.js or any CSS3 property thrown at it. There are options to fine-tune the text, including the ability to set min-max sizes and the level of scaling. Still FitText is only for headlines, and shouldn’t be used with paragraph text.
Alternatives: BigText, Lettering.js, Kerning.js, Kern.js, Type Butter and Slabtext.

7. Responsive Slides
This lightweight plugin allows you to create a responsive slider using elements inside a container. The images have to be the same size and jQuery 1.6 and up should be used. You can keep captions and other non-HTML elements inside the slides, while also using CSS3 transitions with JavaScript fallback. It works in all major desktop and mobile browsers, can support multiple slide shows, have settings for transition and timeout durations, automatic and manual fade, and have options for customization.
Alternatives: Flex Slider, Slides.js, PhotoSwipe, Supersized, Camera, RefineSlide, BlueberrySequence.js and Galleria.

8. Responsive Tables
Data tables in responsive design can be troublesome: you want it to not break responsive layouts, not hide content, let you see entire rows and columns, not be too small to read easily or zoomed in too far requiring scrolling. Here ZURB comes out – a simple JavaScript/CSS combination containing two key files: responsive-tables.js and responsive-tables.css. It works by taking the first column, which is often the unique key for a table, and “pinning” it to the left of the table, allowing you to scroll the other columns under it.
Alternatives: Responsive Data Tables, Stackable.js, Footable, Responsive Tables, Responsive Tables, Responsive SEO Friendly Data Tables.

9. Responsive Design Testing
Building a responsive website means constantly testing how it displays across mobile and tablet devices. You could resize the browser yourself, or use a browser extension or tools within your IDE; but there is an extremely simple tool that allows you to see how a page displays on different screen sizes, in a single view. With Matt Kersley’s RWD testing tool you just have to enter your website’s URL into the address bar to test a specific page in different widths and device sizes. Also you can share the results of the test with others by adding any URL to the end of the testing page address. One major benefit of this tool is that it can be self-hosted (available on GitHub) by downloading and installing it on your own site. You can then navigate through the frames that your website appears in, testing the entire site effortlessly.
Alternatives: Screen Queries, Screenfly, Responsivepx, Responsinator, Responsive ViewportResponsive.is, and Resize My Browser.

10. Respond.js
The problem with media queries in responsive web design is that they are a part of CSS3 specifications so they do not work with older browser versions such as IE8 and lower. Respond.js comes to the rescue for browsers that don’t support media queries directly, translating any media queries it finds into equivalent JavaScript.The script itself is incredibly small and lightweight. It works unobtrusively, and doesn’t rely on any other scripts or frameworks to run.
Alternatives: Modernizer, Adapt, Categorizr, CSS3 Media Queries and Enquire.js.

The tools above are ultra useful for any RWD project from the planning and designing phase right through to testing, and what’re your favorites?

Welcome to share your view points.

Helen Boyarchuk

Helen Boyarchuk
Helen.Boyarchuk@altabel.com
Skype ID: helen_boyarchuk
Business Development Manager (LI page)
Altabel Group – Professional Software Development

Tags: , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,

Within a short period of time since its initial release in late 2009, Node.js has gained the interest of thousands of experienced developers, grown a package manager and a corpus of interesting modules and applications, and even became the reason for a number of startups to appear. You may have heard about node.js, or read articles claiming how great it is; you may have even read some technically focused explanations on why it is so good.

So let’s try to understand what it is about this technology that makes it interesting to developers. And what the commercial pluses of adopting Node.js when developing and deploying web applications.

I’ve carefully look through a number of forums and experts’ opinions in these regards. Below you could find some main reason why it is worth to use Node.js.

* Node.js is a platform for writing high-performance, scalable web applications and network programs in JavaScript. It has an asynchronous, non-blocking, programming model for lightning-fast speeds and enables the use of JavaScript on the server-side so that both client and server run using the same language.

* Node.js was designed to be great at transporting small bits of information around the Internet very quickly, and in real-time. Server-side events, instant messaging apps, real-time games, and collaboration tools are all great example of this.

* Also the reason to use Node.js is based around the idea of not waiting on things. Instead of waiting for a db query to return results, it just triggers a DB query and sets a callback event. Then, while the query is processing, your program can be doing other things (like handling another request). This is what makes Node.js seem so fast.

* Node.js allows designing of scalable applications at a very high speed. The importance of scaling is going to be at a premium for all applications going forward. One of the secrets to Node’s massive scalability is the event-loop. This construct, which is fundamental to the architecture of Node, provides a completely different model for the handling of client connections than those of traditional web server technologies. The event- loop, which your Node.js applications are naturally built upon, transparently treats the connections from your clients extremely lightly. The memory usage per client is negligible, and as such a single Node.js server can handle hundreds of times more clients than a server with other languages.

* Node.js provides non-blocking libraries for database, file and network access. Since I/O is not a fundamental part of JavaScript, nothing had to be taken away to add them. Python’s Twisted and Ruby’s Event Machine have to work around some basic language components in order to get similar evented behavior.

* In addition to the performance wins Node gets “for free” by using the V8 JavaScript engine, the event loop model itself allows Node servers to handle massive concurrencies in network connections very efficiently. It often approaches the benchmarks achieved by high-performance reverse proxies like Nginx (which is also based on an event loop).

* Unlike PHP, Node.js is not “web centric”. Node.js is a general-purpose JavaScript runtime with a host of powerful libraries — one of which happens to provide an HTTP/HTTPS server implementation. With the Node.js it is easy to build command line clients and other TCP/IP servers. This could characterize Node as a quite flexible one, but at the same time, since Node.js isn’t HTTP-centric, you may find yourself having to implement code to do things once provided for you by the framework.

These are only some of the reasons I could provide and answer the question why this library gains popularity and worth to be working with.

Hope this information would be of interest and of use to you. Please feel free to share your thoughts and opinions why we would need to use Node.js. By the way how you think what to expect for it the future?

Natalia Kononchuk

Natalia Kononchuk
Natalia.Kononchuk@altabel.com
Skype ID: natalia_kononchuk
Senior Business Development Manager (LI page)
Altabel Group – Professional Software Development

JavaScript has been popular with the developers for a number of years and has been more discussed than jQuery. However it seems to me that we should also pay attention to jQuery as, I bet, we could find a number of interesting facts about it.

Let`s start from the brief history of the two.

Initially JavaScript was called LiveScript and was invented by Netscape. In 1996 Netscape decided to change its name to raise the popularity of the language by combining it with Java. At that moment Java was used to prepare individual plug-ins. Despite the fact that JavaScript developers have tried to recreate the same syntax and functionality, as in Java, between the two languages, there are many differences. The most important difference is that the Javascript – client is an interpreted scripting language. It runs in the browser without first compilation, which is a mandatory action for programs written in Java…but it is another story.

So JavaScript is a scripting language that is mainly used for website development and client side validation.

The most common use of JavaScript is to write functions that are included in the HTML to interact with HTML elements. For example:
- Sending HTML page data to server using AJAX;
- Animating HTML element;
- Validating the HTML form;
- Storing user information that may help for Web Analytic, Ad tracking etc.

As for jQuery, when it came out in January 2006, from first sight, it looked like a cute hack and in general jQuery was seen as a passing fad. Because the chaining stuff looked like a bit gimmick and the library didn’t look like it would cover all of the bases. Still over the past months we could see that the first impression was wrong, because jQuery encapsulates an extraordinary range of common functionality, and provides a clever plugin API for any functionality not included by default. And the most important thing is that the using of the library obeys best practices and plays well with other JavaScript code.

Mostly jQuery focuses on designers and inexperienced developers, still it could be of interest to experienced programmers as well. Here I will try to enumerate the reasons why:

1) Element’s selecting. Every jQuery operation starts from selecting one or more nodes from the DOM. jQuery’s selection syntax is an interesting hybrid of CSS 1, 2, bits of CSS 3, some XPath and a few custom extensions as well.

2) Namespace. The main point in creating a good JavaScript-code for further using is carefully managed namespace. There is a single global namespace in JavaScript and many programmers clog it without any needs. More sensible developers minimize their intervention to the space using different methods. jQuery introduces the only object in the global namespace: function or object jQuery. Everything else is either direct property jQuery or a method of the object returned by a call to jQuery.

3) The $ function. You could say it is not true that that jQuery introduces only one object in the global namespace as there is also a $: the $ symbol is also set up as a shortcut for jQuery. This makes enough gently: if you want to back your former function $ (for example, if you have a piece of code based on Prototype), you can call jQuery.noConflict (), to return to his old the $. At the beginning you could considere the widespread using $ in jQuery is no more than a clever trick. But for some reason thinking of it in terms of the jQuery symbol makes everything seem a lot more sensible

4) Chaining. jQuery development team often boast about supporting this library call chains, reaching statements like «jQuery created in order to change your style of programming in JavaScript». Frankly speaking, this technique is a big turn-off than the road to the future but you can make good use of jQuery while avoiding lengthy chains of methods entirely. Briefly speaking, the chain can be used for some interesting tricks. In addition to using a set of DOM-samples you can use jQuery-end () method to move the object on the stack and exit the current context. It’s a bit hard to explain, but when you use a method that changes the current (object) context (for example, children () or filter ()), you can use the end () later to return to the previous sample.

5) Manipulating with DOM. jQuery offers a few smart ways of making large scale manipulations to the DOM. The first is quite surprising: the jQuery function can take a snippet of HTML which it will turn in to a DOM element.

6) The returned beast. Object, which is returned by the selectors jQuery, could be quite interesting. It represents a set of DOM-elements and behaves a bit like an array—it has a length property, items can be accessed by index and (most importantly) Firebug treats it as an array when displaying it in the interactive console. This is a clever illusion; the collection is actually a jQuery object, incorporating a large number of methods which can be used to query, modify and extend the collection of selected elements.

There are three principle categories of jQuery methods: those that manipulate all of the matched elements, those that return a value from the first matched object, and those that modify the selection itself. If you have Firebug you can try these out interactively: use this Insert jQuery bookmarklet first to load the jQuery library in to any page, then paste the code examples in to the Firebug console. I would like to note a convenient symmetry of these methods: they are used for display attributes (taking 2 arguments passed to or from a number of properties of the object), and to read the values of these attributes (if only one argument). This symmetry is used throughout jQuery, which greatly facilitates the storage API.

7) Unostentatious programming. The best web applications are those that can still function in disconnected scenarios, and the best method to achieve this is using JavaScript, when the events are assigned to elements only after all the HTML-page are loaded by the user. In jQuery there is excellent support for this approach. First, the paradigm of the selectors to select a node is fundamental for jQuery, and for the non-intrusive programming in general. Second, jQuery provides solutions for window.onload problems

8) jQuery and Ajax. jQuery has the best API for working with Ajax. The most simple form of an Ajax call looks like jQuery(‘div#intro’).load(‘/some/fragment.html’). This performs a GET request against /some/fragment.html and populates div#intro with the returned HTML fragment. It’s a neat shortcut, but what if you want to do something more advanced like display an Ajax loading indicator? jQuery exposes custom events (ajaxStart, ajaxComplete, ajaxError and more) for you to hook in this kind of code.

9) Extensions. Considering the whole set of features as standard, it is worth noting that uzhaty jQuery version is only 20 KB, and even less if you use archive (. Gz). Additional functionality that extends beyond this delivery can be arranged with the help of extensions that can (and do) to add new methods to an existing jQuery. If you want, you can do something like this: jQuery (‘p’). bounceAroundTheScreenAndTurnGreen(); The extension mechanism in jQuery provides documented methods for adding them to the system. Simplicity and ease of use have attracted a large community of authors such extensions, the extensions directory has more than a hundred examples. Another nice feature is the ability to add your own selectors as well as their own methods. MoreSelectors expansion adds methods like div: color (red), which, for example, selects all div with red text.

10) Several words about leaky abstractions. When studying jQuery with more respect, you could struggle with one philosophical blocker. In certain cases, jQuery uses a truly unique methods to achieve a particular function: some parts (such as source code selectors) of this library look scary. If you do so , it requires an understanding of how the library works. To understand this, you need to know some basic concepts, the differences between browsers and a set of methods, which the library uses to get around them. No library can protect you 100% against weird browser behaviour, but as long as you have a grounding in the underlying theory you should be able to figure out if a problem stems from your own code, your library or the underlying implementation.

11) Conclusion. I hope enough evidence was brought to have a positive conclusion about jQuery: it is not a regular library. It contains a lot of interesting ideas that can surprise even the most experienced JavaScript programmers and teach them something new. Even if you will not use it in the work, it is necessary to devote some time and explore the “ecosystem” jQuery.

Elvira Golyak

Elvira Golyak
Elvira.Golyak@altabel.com
Skype ID: elviragolyak
Business Development Manager (LI page)
Altabel Group – Professional Software Development


%d bloggers like this: