Lesson 26

Using Third-Party JavaScript Libraries and Frameworks

What You’ll Learn in This Lesson:

  • Image Why you might use a third-party JavaScript library or framework

  • Image The differences between libraries and frameworks

  • Image How and when you might use Angular, jQuery, React, and other third-party libraries

  • Image How to download and use a popular third-party JavaScript library in your applications

  • Image The benefits of JavaScript frameworks

Third-party JavaScript libraries—that is, code libraries written and maintained by another party for easy implementation in your own code—offer many advantages over always writing your own code. First and foremost, using these libraries enables you to avoid reinventing the wheel for common tasks. In addition, these libraries allow you to implement cross-browser scripting and sophisticated user interface elements without first having to become an expert in JavaScript.

There are many third-party JavaScript libraries out there, and this lesson provides a brief introduction to a few popular ones. In addition, you’ll learn a little about JavaScript frameworks, which—as the name suggests—provide you with some underlying structure for your development, as opposed to just building your own structure and using pieces (libraries) from elsewhere.

Using Third-Party JavaScript Libraries

When you use JavaScript’s built-in and often-used Math and Date functions, JavaScript does most of the work; you don’t have to figure out how to convert dates between formats or calculate a cosine but can just use the function that JavaScript provides. Third-party libraries are libraries that are not directly included with JavaScript, but they serve a similar purpose: They enable you to do complicated things with only a small amount of code because that small amount of code refers to something bigger under the hood that someone else has already created.

Although in general most people are big fans of third-party libraries, you should be aware of some of the common objections:

  • Image You won’t ever really know how the code works because you’re simply employing someone else’s algorithms and functions.

  • Image JavaScript libraries contain a lot of code you’ll never use but that the browser has to download anyway.

Blindly implementing code is never a good thing. You should endeavor to understand what is happening behind the scenes when you use any library. But that understanding could be limited to knowing that someone else wrote a complicated algorithm that you could not write; it’s fine if that’s all you know, as long as you implement it appropriately and understand the possible weaknesses.

The fact that libraries contain a lot of extraneous code should be a consideration if you know that your target users have bandwidth limitations or if the size of the library is disproportionate to the feature you’re using from it. For example, if your code requires the browser to load a 1MB library just to use one function, you should look into ways to fork the library (if it is open source) so you can use just the sections you need, find other features of the library you can use to make it worthwhile, or just look for another library that does what you want but with less overhead.

However, regardless of the objections, there are numerous good reasons for using third-party JavaScript libraries, which in our opinion outweigh the negative objections:

  • Image Using a well-written library can really take away some of the headaches of writing cross-browser JavaScript. You won’t have every browser always at your disposal, but the library writers—and their communities of users—will have tested using several versions of all major browsers, both modern and older.

  • Image Why invent code that somebody else has already written? Popular JavaScript libraries tend to contain the sorts of abstractions that programmers often need to use—which means you’ll likely need those functions too from time to time. The thousands of downloads and pages of online documentation and commentary generated by the most-used libraries pretty much guarantee that the code these libraries contain will be more thoroughly tested and debugged than the ordinary user’s home-cooked code would be.

  • Image Advanced functionality like drag and drop and JavaScript-based animation is, well, really advanced. Truly cross-browser solutions for this type of functionality have always been among the trickiest effects to code for all browsers, and well-developed and -tested libraries to achieve these types of features are incredibly valuable in terms of the time and effort they can save you.

Using a third-party JavaScript library is usually as simple as copying one or more files to your server (or linking to an external but incredibly stable location) and including a <script> tag in your document to load the library, thus making its code available to your own scripts. Several popular JavaScript libraries are introduced in the following sections.

jQuery

jQuery was introduced in 2006 and has grown from an easy, cross-browser means of DOM manipulation to a stable, powerful library. This library contains not just DOM manipulation tools but many additional features that make cross-browser JavaScript coding much more straightforward and productive. In fact, many JavaScript frameworks, which you’ll learn about later in this lesson, rely on the jQuery library for their functionality.

The current version (at this writing) is 3.3.1, and jQuery also has an advanced user interface extensions library, called jQuery UI, that can be used alongside the existing library to rapidly build and deploy rich user interfaces or to add various attractive effects to existing components. In addition, jQuery Mobile is a touch-optimized mobile framework that helps designers make responsive apps and websites that work on mobile devices as well as laptops and desktops.

Note

At jQuery’s home page, http://jquery.com, you can not only download the latest version but also gain access to extensive documentation and sample code. The companion UI library can be found at http://jqueryui.com, and jQuery Mobile is at https://jquerymobile.com.

If you don’t want to download and store the jQuery library on your own local development machine or production server, you can use a remotely hosted version from a content delivery network (CDN), such as the one hosted by Google. Instead of referring to a locally hosted .js file in your HTML files, use the following code to link to a stable and minified version of the code:

<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>

In many cases, this provides better performance than hosting your own version because Google’s servers are optimized for low-latency, massively parallel content delivery. In addition, anyone visiting your page who has also visited another page that references this same file will have the file cached in his or her browser and will not need to download it again. Many of the libraries and frameworks you might want to use are hosted on the Google CDN and other such networks.

jQuery has at its heart a sophisticated, cross-browser method for selection of page elements. The selectors used to obtain elements are based on a combination of simple CSS-like selector styles, so with the CSS techniques you learned in Part III, “Advanced Web Page Design with CSS,” you should have no problem getting up to speed with jQuery. Following are a few brief examples of jQuery code to illustrate this point.

If you want to get an element that has an id of someElement, you simply use the following:

$("#someElement")

You use the pound sign (#) to select for a specific ID, just as with CSS.

To return a collection of elements that have the someClass class name, you can simply use this:

$(".someClass")

You use the period (.) to indicate that you’re selecting elements with a specific class.

You can very simply get or set values associated with selected elements. Suppose, for example, that you want to hide all elements having the class name hideMe. You can do that, in a fully cross-browser manner, with just one line of code:

$(".hideMe").hide();

Manipulating HTML and CSS properties is just as straightforward. To append the phrase “powered by jQuery” to all paragraph elements, for example, you would simply write the following:

$("p").append(" powered by jQuery");

To then change the background color of those same elements, you can manipulate their CSS properties directly, like so:

$("p").css("background-color","yellow");

In addition, jQuery includes simple cross-browser methods for determining whether an element has a class, adding and removing classes, getting and setting the text or innerHTML of an element, navigating the DOM, getting and setting CSS properties, and easily handling events in a cross-browser way.

The associated UI library adds a huge range of UI widgets (such as date pickers, sliders, dialogs, and progress bars), animation tools, drag-and-drop capabilities, and much more.

Note

You can even extend jQuery yourself by writing further plug-ins, or you can use the thousands already submitted by other developers. Browse http://plugins.jquery.com to see lots of examples in searchable categories.

Prototype

Prototype, created by Sam Stephenson, is a JavaScript library that simplifies tasks such as working with DOM objects, dealing with data in forms, and remote scripting (AJAX). By including a single prototype.js file in your document, you have access to many improvements over basic JavaScript.

For example, in other sections of these lessons, you’ve used the getElementById JavaScript method to obtain the DOM object for an element within a web page. Prototype includes an improved version of this: the $ function. Not only is the Prototype function easier to type, but it also is more sophisticated than the built-in function and supports multiple objects.

Adding Prototype to your pages requires only one file, prototype.js, and one <script> tag, such as the following:

<script src="prototype.js"></script>

Alternatively, you can get Prototype from a CDN and refer to it, just as in the jQuery example in the preceding section.

Note

Prototype is free, open-source software. You can download it from its official website at www.prototypejs.org. Prototype is also built into the Ruby on Rails framework for the server-side language Ruby; see https://rubyonrails.org for more information.

script.aculo.us

By the end of these lessons, you will have learned to do some useful things with JavaScript, often involving complex code. But you can also include impressive effects in your pages by using a prebuilt library and only a few lines of code.

script.aculo.us by Thomas Fuchs is one such library. It includes functions to simplify drag-and-drop tasks, such as rearranging lists of items. It also includes a number of combination effects, which enable you to use highlighting and animated transitions within your pages. For example, a new section of the page can be briefly highlighted in yellow to get the user’s attention, or a portion of the page can fade out or slide off the screen.

Caution

While script.aculo.us is still widely used by many designers, it has not been updated since 2010 and may not have all the modern features you want.

After you’ve included the appropriate files, using effects is as easy as using any of JavaScript’s built-in methods. For example, the following statements use script.aculo.us to fade out an element of the page with the id value test:

obj = document.getElementById("test");
new Effect.Fade(obj);

script.aculo.us is built on the Prototype framework, described earlier in this lesson, and it includes all the functions of Prototype; therefore, you could also simplify the preceding example further by using the $ function, like so:

new Effect.Fade($("test"));

The library’s name, script.aculo.us, is also the URL where you get it.

Note

The next section shows a script that demonstrates several script.aculo.us effects.

Other Popular JavaScript Libraries

There are many more JavaScript libraries out there, and more are appearing all the time as JavaScript is taken more seriously as an application development language. Here are two more libraries you might want to explore:

  • Image Dojo (www.dojotoolkit.org)—This is an open-source toolkit that adds power to JavaScript to simplify building applications and user interfaces. It adds features ranging from extra string and math functions to animation and AJAX.

  • Image MooTools (https://mootools.net)—This is an open-source object-oriented JavaScript library. Its focus is on reusability and modularity.

Adding JavaScript Effects by Using a Third-Party Library

To see how simple it is to use an external library, in this section you’ll create a sample script that includes the script.aculo.us library and uses event handlers to demonstrate several of the available effects.

Caution

This example was created using version 1.9.0 of script.aculo.us and version 1.7.3.0 of Prototype. The script should work with later versions because developers tend to ensure backward compatibility, but the underlying code might have changed since this lesson was written. If you have trouble, you might need to use these specific versions.

This example shows how to include script.aculo.us and Prototype in an HTML document by leveraging the Google CDN. To do this, simply use <script> tags to reference the code:

<script
   src="http://ajax.googleapis.com/ajax/libs/prototype/1.7.2.0/prototype.js">
</script>
<script
   src="http://ajax.googleapis.com/ajax/libs/scriptaculous/1.9.0/scriptaculous.js">
</script>

Note

Of course, you could download script.aculo.us and Prototype to your local development machine or web server and reference it accordingly. If you go down that path, try to keep all your assets in separate directories, such as a js folder that contains all JavaScript libraries, and ensure that your <script> tag references the path accordingly.

If you include these statements in the <head> section of your document, the library functions will be available to other scripts or event handlers anywhere in the page. But remember that when you place the scripts first, the browser won’t load anything until those scripts are loaded—one at a time. Most developers include libraries in the <head> of their documents but place them last. But it’s not required to place them there. As long as the link to the library is placed above any scripts that use it, you can place it below all your HTML, just as you would any other script.

After you have included the external code, you simply need to include a bit of JavaScript to trigger the effects. This section uses a section of the page wrapped in a <p> tag with the id value testarea to demonstrate some of the effects that script.aculo.us makes possible. Each effect is triggered by a simple event handler on a button. For example, this code defines the Fade Out button:

<button onclick="new Effect.Fade($('testarea'))">Fade Out</button>

This code uses the $ function that is built in to Prototype to obtain the object for the element with the id value testarea and then passes it to the Effect.Fade function that is built in to script.aculo.us.

Note

This example demonstrates 6 effects: Fade, Appear, SlideUp, SlideDown, Highlight, and Shake. There are more than 16 effects in the library, plus methods for supporting drag-and-drop and other features. See script.aculo.us for details.

Once you have included the script.aculo.us library, you can combine effects with event handlers and some sample text to see a complete demonstration of script.aculo.us effects. The complete HTML document for this example is shown in Listing 26.1.

Listing 26.1 The Complete Library Effects Example

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Testing script.aculo.us effects</title>
    <style>
      #testarea {
        background-color:#CCC; margin:20px; padding:10px;
      }
    </style>
    <meta name="viewport"
          content="width=device-width, initial-scale=1">
    <script
src="https://ajax.googleapis.com/ajax/libs/prototype/1.7.3.0/prototype.js">
    </script>
    <script
src="https://ajax.googleapis.com/ajax/libs/scriptaculous/1.9.0/scriptaculous.js">
    </script>
  </head>
  <body>
    <h1>Testing script.aculo.us Effects</h1>
    <button onclick="new Effect.Fade($('testarea'))">Fade Out</button>
    <button onclick="new Effect.Appear($('testarea'))">Fade In</button>
    <button onclick="new Effect.SlideUp($('testarea'))">Slide Up</button>
    <button onclick="new Effect.SlideDown($('testarea'))">Slide Down</button>
    <button onclick="new Effect.Highlight($('testarea'))">Highlight
       </button>
    <button onclick="new Effect.Shake($('testarea'))">Shake</button>
    <hr>
    <h2>Testing Effects</h2>
    <p id="testarea">
    This section of the document is within a &lt;p&gt; element with
    the <strong>id</strong> value of <strong>testarea</strong>. The
    event handlers on the buttons above send this object to the
    <a href="http://script.aculo.us/">script.aculo.us</a> library
    to perform effects. Click the buttons to see the effects in action.    
    </p>
  </body>
</html>  

This document starts with two <script> tags to include the third-party files that contain the JavaScript code that your own scripts will reference. The effects themselves are triggered by the event handlers defined for each of the six buttons. The <p> section at the end defines the testarea element that will be used to demonstrate the effects.

When you load this script in your web browser, the display should look as shown in Figure 26.1. After it has been loaded, you should be able to click on any of the six buttons at the top of the page to trigger the effects provided by the script.aculo.us JavaScript library.

A screenshot shows how to implement effects using JavaScript. The page has six buttons: Fade Out, Fade In, Slide Up, Slide Down, Highlight, and Shake. A text is displayed at the bottom for testing the effects.
Figure 26.1 The JavaScript effects example, ready for action.

Using JavaScript Frameworks

There’s a big difference between JavaScript libraries and JavaScript frameworks: Simple libraries tend to be smaller and provide ready-made pieces of code that provide functionality meant to enhance your custom architecture, and frameworks are larger, are more complicated, and impose an architectural pattern upon your application, such as the model-view-controller (MVC) pattern. In an MVC pattern, an application is conceived of as having three interconnected components:

  • Image Model—Acts as the central component, even though it’s listed first in the name, holding application data, business rules, functions, and other logical elements

  • Image View—Requests information from the model to show to the user

  • Image Controller—Sends information to the model for processing through user interactions

You can think of it this way: In a web-based application, the user interacts with a controller that manipulates the underlying model, which updates the view, which the user then sees in the web browser.

In a traditional web-based application, you will likely have experienced it this way: Both the model and the controller components sit on the back end, away from the browser, and are invoked through form elements or other interactions by the user that say, “Hey, back-end script, go do something with logic and data based on this input I’m giving you, and send the result back to the screen.” The screen, in this case, would contain dynamically generated HTML (the view).

In a JavaScript-based MVC application, which most likely has been developed using one of the frameworks you’ll learn about in a moment, all three components can sit on the client side; that is to say, a user can interact with data that is stored and manipulated entirely within the front end, never touching a back-end script or database. Or most of the three components can sit on the front end and use AJAX requests to invoke a script on the back end, which then sends results back into the view.

Note

AJAX (Asynchronous JavaScript and XML), also known as remote scripting, enables JavaScript to communicate with a program running on the web server. This means JavaScript can do things that were traditionally not possible, such as dynamically loading information from a database or storing data on a server without refreshing a page.

AJAX requires some complex scripting, particularly because the methods you use to communicate with the server vary depending on the browser in use. Fortunately, many libraries have been created to fill the need for a simple way to use AJAX.

By the end of these introductory lessons in HTML, CSS, and JavaScript, we wouldn’t expect you or anyone else to be prepared to create a JavaScript framework of your very own—and please don’t, because there are already 30 or more competing frameworks out there in the wild! But we would expect you to be able to start thinking about how a framework might be helpful in your work and to be able to begin understanding one or more of the major frameworks in use today.

If you are building a predominantly read-only website and using a little JavaScript or jQuery for some display features, a framework would be considerable overkill. But if you begin to think about ways to extend that website to include user interactivity, you might think about laying a framework in to handle that work for you. Following are some major JavaScript frameworks in use today, all of which would be fine starting points for further exploration:

  • Image Angular (https://angular.io)—This is a very powerful and flexible framework, but it involves a steep learning curve. However, it has a very active user community that is ready to help new developers understand the framework. It is a complete makeover of the equally popular original framework, AngularJS (https://angularjs.org).

  • Image Backbone.js (backbonejs.org)—This framework has been around for quite some time (relatively speaking) and served as the inspiration for many other frameworks. It enables a new developer to get started quickly, but the downside of that, for some, is that the applications will contain a lot of unused templating code.

  • Image Ember (https://emberjs.com)—Like Backbone.js, Ember enables a new developer to get started quickly. Although it appears “too magical” to some, Ember’s strong adherence to common programming idioms can be a benefit to new developers.

  • Image Knockout (knockoutjs.com)—Less popular than the frameworks previously listed, Knockout nonetheless provides a strong alternative as well as several nice tutorials for new developers.

  • Image React (https://reactjs.org)—There is some debate over whether React is a library or a framework, but whatever it is, it’s a popular tool for creating interactive web pages and applications, and it has been growing in popularity.

There are many more than these few JavaScript frameworks out there at the time of this writing, and we fully expect that there will be more in years to come. To stay up to date or to get an overview of the core features of JavaScript frameworks and libraries, you can start by bookmarking and revisiting JavaScripting (www.javascripting.com).

Summary

In this lesson, you learned about some of the many third-party libraries available for JavaScript, which offer many advantages, including easy cross-browser scripting, selection and editing of HTML and CSS values, animation, and more sophisticated user-interface tools, such as drag-and-drop. You used the script.aculo.us and Prototype libraries to put some basic JavaScript effects like this into action.

In addition, you learned about some of the popular JavaScript frameworks, and how you can take advantage of them to develop feature-rich web applications following standard software architecture patterns such as the model-view-controller (MVC) pattern.

Q&A

Q. Can I use more than one third-party library in the same script?

A. Yes, in theory: If the libraries are well written and designed not to interfere with each other, there should be no problem with using them both in the same script. In practice, this will depend on the libraries you need and how they were written, but many JavaScript libraries can be used together or will include a warning about incompatibilities.

Q. Can I build my own library to simplify scripting?

A. Yes. As you deal with more complicated scripts, you’ll find yourself using the same functions over and over, and if they’re functions you have created, then storing them in a separate library file may be a good idea. This process is as simple as creating a .js file with your code, placing it on your server, and referencing it in a <script> tag as you would any other library.

Workshop

The Workshop contains quiz questions and activities to help you solidify your understanding of the material covered. Try to answer all questions before looking at the “Answers” section that follows.

Quiz

1. Which of the following objects is not a JavaScript library?

  1. script.aculo.us

  2. Yahoo! UI

  3. AJAX

2. How can you extend jQuery yourself?

  1. jQuery can’t be extended.

  2. You can write server-side scripts.

  3. You can write a plug-in or use a prewritten one.

3. What other JavaScript third-party library does script.aculo.us employ?

  1. Prototype

  2. Dojo

  3. jQuery

4. What is a drawback to using JavaScript libraries?

  1. You don’t know how the code works because you didn’t write it.

  2. The code often has more in it than you need, bloating your pages.

  3. Many libraries have malicious code in them.

  4. Both A and B

5. What is your option if you don’t want to download and store a library on your own server?

  1. Use a CDN

  2. Use a hosting provider

  3. Use another library

  4. Use PHP

6. What does the following jQuery snippet do?

$("em.bright").css("background-color","pink");

  1. Select all elements with the em and bright classes and change their background colors to pink.

  2. Select all <em> elements with the class bright and change their background color to pink.

  3. Select all elements with the bright class and make them <em> elements with a pink background.

  4. Select the first <em> element with the class bright and change its background color to pink.

7. What Prototype function replaces getElementById?

  1. There is no Prototype function that replaces getElementById.

  2. The getElement function

  3. The byId function

  4. The $ function

8. Why do you include script libraries in the <head> of your documents?

  1. Then they can be accessed by any script on the page.

  2. This is where they are required to be.

  3. Libraries load asynchronously, so they can be placed first.

  4. You should never include them in the <head>.

9. What does MVC stand for in programming architecture?

  1. Massive version change

  2. Multiuse-view-controller

  3. Model-view-controller

  4. Mobile-view-controller

10. What are three popular JavaScript frameworks in use today?

  1. Angular, JSEmber, and React

  2. AngularJS, Ember, and React

  3. AngularJS, Backbone.js, and Knockact

  4. Backbone.js, Ember, and Knockact

Note

Just a reminder for those of you reading these words in the print or e-book edition of this book: If you go to www.informit.com/register and register this book (using ISBN 9780672338083), you can receive free access to an online Web Edition that not only contains the complete text of this book but also features an interactive version of this quiz.

Answers

1. c. AJAX is a programming technique that enables your scripts to use resources hosted on your server. There are many libraries to help you employ AJAX functionality, but AJAX itself is not a library.

2. c. jQuery has a well-documented method for writing and using plug-ins.

3. a. script.aculo.us uses the Prototype library.

4. d. You don’t know how the code works because you didn’t write it, and libraries often contain a lot of extra code that you don’t need but that the browser has to download anyway.

5. a. You can use a content delivery network (CDN).

6. b. This snippet selects all the <em> tags with the class bright and gives them the background color pink.

7. d. The $ function is an improved version in Prototype.

8. a. Most designers include them there because then they can be accessed by any script.

9. c. MVC is the model-view-controller pattern.

10. b. Some popular frameworks include Angular (and AngularJS), Backbone.js, Ember, Knockout, and React.

Exercises

  • Image Visit the script.aculo.us website at script.aculo.us to find the complete list of effects and then modify Listing 26.1 to add buttons for one or more of these additional effects.

  • Image Much as you practiced in this lesson using script.aculo.us, pick another third-party JavaScript library such as Dojo or MooTools and implement one or more of the library’s custom features on your own. If you don’t want to use either of those, you can pick one from the list at www.javascripting.com.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.213.235