Summary of skills related to optimizing the RequireJS project.

Source: Internet
Author: User

Summary of skills related to optimizing the RequireJS project.

This article demonstrates how to merge and compress a RequireJS-based project. This article will use a painstaking tool, including Node. js. Therefore, if you do not have Node. js, click here to download one.
Motivation

Many articles have been introduced about RequireJS. This tool can easily split your JavaScript code into modules and keep your code modular and easy to maintain. In this way, you will obtain some JavaScript files with mutual dependencies. You only need to reference A RequireJS-Based Script file in your HTML document. All necessary files will be automatically referenced on this page.

However, it is a bad practice to separate all JavaScript files in the production environment. This will cause many requests, even if these files are small, it will waste a lot of time. You can merge these script files to reduce the number of requests and Save loading time.

Another method to Save loading time is to reduce the size of these loaded files, and smaller files will be transmitted faster. This process is called minification. It is implemented by carefully changing the code structure of the script file without changing the code form (behavior) and function (functionality. For example, remove unnecessary spaces, shorten (mangling, or both compress) variables (variables) names and functions (methods, or methods) names, and so on. This process of merging and compressing files is called code optimization ). In addition to optimizing JavaScript files, this method is also suitable for CSS file optimization.

RequireJS has two main methods: define () and require (). These two methods basically have the same definition (declaration) and they all know how to load dependencies, and then execute a callback function ). Unlike require (), define () is used to store code as a named module. Therefore, the callback function of define () must have a return value defined as this module. These similar modules are called AMD (Asynchronous Module Definition, Asynchronous Module Definition ).

If you are not familiar with RequireJS or do not understand what I wrote-don't worry. The following is an example.
 
Optimization of JavaScript applications

In this section, I will show you how to optimize the TodoMVC Backbone. js + RequireJS project of Addy Osmani. Because 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 decompress the downloaded zip file. The decompressed directory of todo-mvc will be the root directory (root path) of our example. From now on, I will reference this directory as <root>.

View the source code of <root>/index.html, and you will find that it contains only one script tag (the other one is referenced when you use Internet Explorer ):
Code for index.html to reference a script file
 

<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 reference the require. js script file. If you run this project in your browser and in the network tag of your favorite debugging tool, you will find that the browser also loads other JavaScript files:

All script files in the Red Line border are automatically loaded by RequireJS.


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

RequireJS Optimizer has a lot of use. It not only optimizes a single JavaScript or CSS file, but also optimizes the entire project or a portion of it, or even multi-page applications ). It can also use different minification engines or no minification at all. This article does not intend to cover all possibilities of RequireJS Optimizer, and only demonstrates one of its usage here.

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

$ node r.js -o <arguments>

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

$ 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 contain the specified parameters:
 

$ node r.js -o build.js

Build. js content: parameters in the configuration file
 

({  baseUrl: ".",  name: "main",  out: "main-built.js"})

I think building a configuration file is more readable than using parameters in the command line, so I will use this method. Next, we will create a <root>/build. js file for the project, which includes the following parameters: <root>/build. j

({  appDir: './',  baseUrl: './js',  dir: './dist',  modules: [    {      name: 'main'    }  ],  fileExclusionRegExp: /^(r|build)\.js$/,  optimizeCss: 'standard',  removeCombined: true,  paths: {    jquery: 'lib/jquery',    underscore: 'lib/underscore',    backbone: 'lib/backbone/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 is not the purpose of this Article to understand all the configuration items of RequireJS Optimizer, but I want to explain (description) the parameters I used in this article:

To learn more about RequireJS Optimizer and more advanced applications, you can click here to view detailed information about all available configuration options in addition to the information provided on its webpage.

Now that you have a build file, you can run the optimizer. Go to the <root> directory and run the following command:
Optimizer)
 
$ Node r. js-o build. js
A new folder is generated: <root>/dist. It is important to note that <root>/dist/js/main. js now contains all the files that have been merged and compressed with dependencies. In addition, <root>/dist/css/base.css is also optimized.

The optimized project looks exactly the same as the project before optimization. Check the network traffic information of the page. Only two JavaScript files are loaded.

RequireJs Optimizer reduces the number of script files on the server from 13 to 2 and 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 reference the require. js file. Because there are no separated script files and all the dependent files have been loaded.

Even so, the optimization process combines all our scripts to generate an optimized script file, which contains many define () and require () calls. Therefore, to ensure that the application runs properly, define () and require () must specify and implement somewhere in the application (that is, including these files ).

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 considerations (infrastructure considerations ). When we develop a JavaScript library, this problem becomes particularly serious. Compared with RequireJS, these libraries are usually very small, so it may cause a huge overhead to include them in the library.

At the time of writing this article, there was no complete solution for this overhead, but almond can be used to alleviate this problem. Almond is an extremely simple AMD loader that implements the RequireJS interface (API ). Therefore, it can be used to replace the RequireJS implementation in the optimized code. We can include almond in the project.
For example, I am working on developing an optimizer that will be able to optimize the RequireJS application without overhead, but it is still a new project (in the early stages of development) so there is no demonstration of it here.
Download and summary

  • Download the unoptimized TodoMVC Backbone. js + RequireJS project or view it.
  • Download the optimized TodoMVC Backbone. js + RequireJS Project (under the dist folder) or view it.

Related Article

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.