Home Web Front-end JS Tutorial Summary of related techniques for optimizing RequireJS projects_Basic knowledge

Summary of related techniques for optimizing RequireJS projects_Basic knowledge

May 16, 2016 pm 03:52 PM

This article will demonstrate how to merge and compress a RequireJS-based project. This article will use several tools, including Node.js. Therefore, if you don’t have Node.js on hand yet, you can click here to download one.
Motivation

There have been many articles introduced about RequireJS. This tool can easily split your JavaScript code into modules and keep your code modular and maintainable. This way, you will have a number of JavaScript files that have interdependencies. Just reference a RequireJS-based script file in your HTML document, and all necessary files will be automatically referenced to the page.

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

Another trick to save loading time is to reduce the size of the files being loaded. Smaller files will transfer faster. This process is called minimization, and it is achieved by carefully changing the code structure of the script file without changing the code's behavior and functionality. For example: remove unnecessary spaces, shorten (mangling, or compress) variable (variables, or method) names and function (methods, or method) names, etc. This process of merging and compressing files is called code optimization. In addition to optimizing JavaScript files, this method is also suitable for optimizing CSS files.

RequireJS has two main methods: define() and require(). These two methods basically have the same declaration and they both 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() needs to have a return value as this module definition. These similarly defined modules are called AMD (Asynchronous Module Definition, asynchronous module definition).

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

Optimization of JavaScript applications

In this section I will show you how to optimize Addy Osmani's 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 app and unzip the downloaded zip file. The unzipped directory of todo-mvc will be the root path for our example, and I will refer to this directory as from now on.

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

<script data-main="js/main" src="js/lib/require/require.js"></script>
<!--[if IE]>
  <script src="js/lib/ie.js"></script>
<![endif]-->
Copy after login

其实,整个项目只需要引用require.js这个脚本文件。如果你在浏览器中运行这个项目,并且在你喜欢的(擅长的)调试工具的network标签中, 你就会发现浏览器同时也加载了其它的JavaScript文件:

201571115405671.png (843×400)

所有在红线边框里面的脚本文件都是由RequireJS自动加载的。


我们将用RequireJS Optimizer(RequireJS优化器)来优化这个项目。根据已下载的说明文件,找到r.js并将其复制到目录。 jrburke的r.js是一个能运行基于AMD的项目的命令行工具,但更重要的是,它包含RequireJS Optimizer允许我们对脚本文件(scripts)合并与压缩。

RequireJS Optimizer有很多用处。它不仅能够优化单个JavaScript或单个CSS文件,它还可以优化整个项目或只是其中的一部分,甚至多页应用程序(multi-page application)。它还可以使用不同的缩小引擎(minification engines)或者干脆什么都不用(no minification at all),等等。本文无意于涵盖RequireJS Optimizer的所有可能性,在此仅演示它的一种用法。

正如我之前所提到的,我们将用到Node.js来运行优化器(optimizer)。用如下的命令运行它(optimizer):
运行RequireJS Optimizer

$ node r.js -o <arguments>
Copy after login

有两种方式可以将参数传递给optimizer。一种是在命令行上指定参数:
在命令行上指定参数

$ node r.js -o baseUrl=. name=main out=main-built.js
Copy after login

另一种方式是构建一个配置文件(相对于执行文件夹)并包含指定的参数 :

$ node r.js -o build.js
Copy after login

build.js的内容:配置文件中的参数

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

我认为构建一个配置文件比在命令行中使用参数的可读性更高,因此我将采用这种方式。接下来我们就为项目创建一个/build.js文件,并且包括以下的参数: /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'
    }
  }
})
Copy after login


Understanding all the configuration options of RequireJS Optimizer is not the purpose of this article, but I want to explain (describe) the parameters I used in this article:

201571115426354.jpg (767×415)

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

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

$ node r.js -o build.js
A new folder will be generated: /dist. It's important to note that /dist/js/main.js now contains all the files with dependencies that have been merged and compressed. In addition, /dist/css/base.css has also been optimized.

Run the optimized project and it will look exactly like the unoptimized project. Checking the network traffic information of the page again, you will find that only two JavaScript files are loaded.

201571115538676.png (843×167)

RequireJs Optimizer reduces the number of script files on the server from 13 to 2 and reduces the total file size 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 files with dependencies have been loaded.

Nonetheless, the optimization process merged all our scripts into one optimized script file, which contains many define() and require() calls. Therefore, in order to ensure that the application can run properly, define() and require() must be specified and implemented somewhere in the application (that is, including these files).

This results in a well-known overhead: we always have some code implementing define() and require(). This code is not part of the application; it exists solely for our infrastructure considerations. This problem becomes especially huge when we develop a JavaScript library. These libraries are usually very small compared to RequireJS, so including it in the library creates a huge overhead.

As I write this, there is no complete solution for this overhead, but we can use almond to alleviate this problem. Almond is an extremely simple AMD loader that implements the RequireJS interface (API). Therefore, it can be used as an alternative to the RequireJS implementation in optimized code, and we can include almond in the project.
As such, I'm working on developing an optimizer that will be able to optimize RequireJS applications without the overhead, but it's still a new project (in the early stages of development) so there's nothing to show about it here .
Download and Summary

  •  Download the unoptimized TodoMVC Backbone.js RequireJS project or check out it.
  •  Download the optimized TodoMVC Backbone.js RequireJS project (located under the dist folder) or view it.
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How do I create and publish my own JavaScript libraries? How do I create and publish my own JavaScript libraries? Mar 18, 2025 pm 03:12 PM

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

How do I optimize JavaScript code for performance in the browser? How do I optimize JavaScript code for performance in the browser? Mar 18, 2025 pm 03:14 PM

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

How do I debug JavaScript code effectively using browser developer tools? How do I debug JavaScript code effectively using browser developer tools? Mar 18, 2025 pm 03:16 PM

The article discusses effective JavaScript debugging using browser developer tools, focusing on setting breakpoints, using the console, and analyzing performance.

How do I use Java's collections framework effectively? How do I use Java's collections framework effectively? Mar 13, 2025 pm 12:28 PM

This article explores effective use of Java's Collections Framework. It emphasizes choosing appropriate collections (List, Set, Map, Queue) based on data structure, performance needs, and thread safety. Optimizing collection usage through efficient

How do I use source maps to debug minified JavaScript code? How do I use source maps to debug minified JavaScript code? Mar 18, 2025 pm 03:17 PM

The article explains how to use source maps to debug minified JavaScript by mapping it back to the original code. It discusses enabling source maps, setting breakpoints, and using tools like Chrome DevTools and Webpack.

Getting Started With Chart.js: Pie, Doughnut, and Bubble Charts Getting Started With Chart.js: Pie, Doughnut, and Bubble Charts Mar 15, 2025 am 09:19 AM

This tutorial will explain how to create pie, ring, and bubble charts using Chart.js. Previously, we have learned four chart types of Chart.js: line chart and bar chart (tutorial 2), as well as radar chart and polar region chart (tutorial 3). Create pie and ring charts Pie charts and ring charts are ideal for showing the proportions of a whole that is divided into different parts. For example, a pie chart can be used to show the percentage of male lions, female lions and young lions in a safari, or the percentage of votes that different candidates receive in the election. Pie charts are only suitable for comparing single parameters or datasets. It should be noted that the pie chart cannot draw entities with zero value because the angle of the fan in the pie chart depends on the numerical size of the data point. This means any entity with zero proportion

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

See all articles