Summary of relevant skills in optimizing Requirejs project

Source: Internet
Author: User
Tags script tag

This article demonstrates how to merge and compress a Requirejs based project. This article will use a hard tool, including node.js. So if you don't have node.js on hand, click here to download one.

Motivation

A lot of articles about Requirejs have been introduced. This tool can easily split your JavaScript code into hard modules (module) and keep your code modular and maintainable. This way, you'll get some JavaScript files that have dependencies on each other. Simply refer to a Requirejs script file in your HTML document, and all the necessary files will be automatically referenced on this page.

However, it is a bad practice to detach all JavaScript files in a production environment. This can lead to many requests (requests), even if the files are small and waste a lot of time. You can combine these script files to reduce the number of requests to achieve the purpose of saving load time.

Another technique for saving load time is to reduce the size of these loaded files, and relatively small files can be transferred faster. This process is called minimization (minification), which is achieved by carefully altering the code structure of the script file and not changing the shape of the Code (behavior) and functionality (functionality). For example: Remove unnecessary spaces, shorten (mangling, or compress) variable (variables) names and functions (methods, or method) names, and so on. The process of merging and compressing files is called Code optimization (optimization). This approach is also useful for optimizing CSS files, in addition to optimizing (optimization) JavaScript files.

Requirejs has two main methods (method): Define () and require (). The two methods essentially have the same definition (declaration) and they all know how to load the dependencies and then execute a callback function (callback functions). Unlike require (), define () is used to store code as a named module. Therefore, the callback function for define () needs to have a return value as the module definition. These similarly defined modules are called AMD (Asynchronous module definition, asynchronous modules definitions).

If you're not familiar with Requirejs or don't quite understand what I'm writing-don't worry. Here is an example of these.

Optimization of JavaScript applications

In this section I will show you how to optimize the Addy Osmani TODOMVC backbone.js + Requirejs project. Since the TODOMVC project contains many TODOMVC implementations under different frameworks, I downloaded version 1.1.0 and extracted the Backbone.js + Requirejs application. Click here to download the application and unzip the downloaded zip file. TODO-MVC's extract directory will be the root of our example (root path), and from now on I will refer to this directory as .

Looking at the source code of the/index.html, you will find that it contains only one script tag (the other is referenced when you use Internet Explorer):

Index.html code that references script files

?

1 2 3 4 <script data-main= "Js/main" src= "Js/lib/require/require.js" ></script> <!--[if ie]> <script src= "Js/lib/ie.js" ></script> <! [endif]-->

In fact, the entire project only needs to refer to require.js this script file. If you run this project in a browser, and in the Network tab of your favorite debugging tool, you'll find that the browser also loads other JavaScript files:

All the script files that are inside the red line border are automatically loaded by Requirejs.

We will use the Requirejs Optimizer (Requirejs optimizer) to optimize this project. Based on the downloaded documentation, locate the r.js and copy it to the directory. Jrburke's r.js is a command-line tool that can run AMD based projects, but more importantly, it contains Requirejs optimizer allows us to merge and compress script files (scripts).

Requirejs Optimizer has many uses. Not only can it optimize a single javascript or a single CSS file, it can also optimize an entire project or just a subset of it, or even a multi-page application (multi-page application). It can also use a different zoom engine (minification engines) or simply do nothing (no minification at all), and so on. This article is not intended to cover all the possibilities of Requirejs optimizer, where it only demonstrates one usage.

As I mentioned earlier, we will use Node.js to run the optimizer (optimizer). Run it with the following command (optimizer):

Run Requirejs Optimizer

?

1 $ node R.js-o <arguments>

There are two ways to pass parameters to optimizer. One is to specify the parameters on the command line:

Specifying parameters on the command line

?

1 $ node R.js-o baseurl=. Name=main Out=main-built.js

Another way is to build a configuration file (relative to the execution folder) and include the specified parameters:

?

1 $ node R.js-o build.js

Build.js content: Parameters in the configuration file

?

1 2 3 4 5 ({baseurl: ".", Name: "Main", Out: "Main-built.js"})

I think building a profile is more readable than using parameters on the command line, so I'll take that approach. Next we create a/build.js file for the project and include the following parameters: /build.j

?

1, 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 {appdir: './', BaseURL: './js ', dir: './dist ', modules: [{name: ' main '}], Fileexclusionregexp:/^ (r|build). js$/, opt IMIZECSS: ' Standard ', removecombined:true, paths: {jquery: ' Lib/jquery ', underscore: ' Lib/underscore ', backbone: ' lib/b Ackbone/backbone ', backbonelocalstorage: ' Lib/backbone/backbone.localstorage ', text: ' Lib/require/text '}, Shim: { Underscore: {exports: ' _ '}, Backbone: {deps: [' underscore ', ' jquery '], exports: ' Backbone '}, Backbonelocalstorage: { Deps: [' backbone '], exports: ' Store '}}}

It's not the purpose of this article to figure out all the configuration items for Requirejs optimizer, but I want to explain (describe) the parameters I used in this article:

For more information on Requirejs Optimizer and more advanced applications, you can click here to see the details of all available configuration options, in addition to the information provided earlier in the page.

Now that you have a build file, you can run the optimizer (optimizer). Enter the directory and execute the following command:

Run Optimizer (optimizer)

$ node R.js-o build.js

A new folder will be generated: /dist. It is important to note that the /dist/js/main.js now contains all the dependent files that have been merged and compressed. In addition, /DIST/CSS/BASE.CSS has been optimized.

After you run the optimized project, it looks exactly the same as before the project was not optimized. Check the network transfer (network traffic) information for this page and find that only two JavaScript files are loaded.

Requirejs Optimizer reduces the script files on the server from 13 to 2 and reduces the total size of the files from 164KB to 58.6KB (Require.js and Main.js).

Overhead

Obviously, after optimization, we no longer need to refer to the Require.js file. Because there are no separate script files and all dependent files have been loaded.

Nonetheless, the optimization process combines all of our scripts to generate an optimized script file that contains many define () and require () calls. Therefore, to ensure that the application works correctly, define () and require () must be specified and implemented somewhere in the application (that is, the files are included).

This leads to a well-known overhead: we always have some code to implement define () and require (). These codes are not part of the application, they exist only for our infrastructure consideration (infrastructure considerations). When we develop a JavaScript library (JavaScript libraries), this problem becomes particularly significant. These libraries are usually small compared to requirejs, so including them in the library can create a huge overhead.

While I'm writing this article, there's not a complete solution to this overhead, but we can use almond to mitigate the problem. Almond is a very simple AMD loader that implements the Requirejs interface (API). Therefore, it can be used to replace the REQUIREJS implementation in the optimized code, and we can include almond in the project.

As a result, I'm working on an optimizer (optimizer) that will be able to optimize the Requirejs application without overhead, but it's still a new project (in the early stages of development) so there's nothing to show about it.

Download and summary

Download the TODOMVC Backbone.js + Requirejs project or view it.

Download the optimized TODOMVC Backbone.js + Requirejs project (located under the Dist folder) or view it.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.