search
HomeWeb Front-endJS TutorialSummary of related techniques for optimizing RequireJS projects_Basic knowledge

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]-->

其实,整个项目只需要引用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>

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

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

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

$ node r.js -o build.js

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

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

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


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
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
Replace String Characters in JavaScriptReplace String Characters in JavaScriptMar 11, 2025 am 12:07 AM

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

Custom Google Search API Setup TutorialCustom Google Search API Setup TutorialMar 04, 2025 am 01:06 AM

This tutorial shows you how to integrate a custom Google Search API into your blog or website, offering a more refined search experience than standard WordPress theme search functions. It's surprisingly easy! You'll be able to restrict searches to y

Build Your Own AJAX Web ApplicationsBuild Your Own AJAX Web ApplicationsMar 09, 2025 am 12:11 AM

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

Example Colors JSON FileExample Colors JSON FileMar 03, 2025 am 12:35 AM

This article series was rewritten in mid 2017 with up-to-date information and fresh examples. In this JSON example, we will look at how we can store simple values in a file using JSON format. Using the key-value pair notation, we can store any kind

8 Stunning jQuery Page Layout Plugins8 Stunning jQuery Page Layout PluginsMar 06, 2025 am 12:48 AM

Leverage jQuery for Effortless Web Page Layouts: 8 Essential Plugins jQuery simplifies web page layout significantly. This article highlights eight powerful jQuery plugins that streamline the process, particularly useful for manual website creation

What is 'this' in JavaScript?What is 'this' in JavaScript?Mar 04, 2025 am 01:15 AM

Core points This in JavaScript usually refers to an object that "owns" the method, but it depends on how the function is called. When there is no current object, this refers to the global object. In a web browser, it is represented by window. When calling a function, this maintains the global object; but when calling an object constructor or any of its methods, this refers to an instance of the object. You can change the context of this using methods such as call(), apply(), and bind(). These methods call the function using the given this value and parameters. JavaScript is an excellent programming language. A few years ago, this sentence was

Improve Your jQuery Knowledge with the Source ViewerImprove Your jQuery Knowledge with the Source ViewerMar 05, 2025 am 12:54 AM

jQuery is a great JavaScript framework. However, as with any library, sometimes it’s necessary to get under the hood to discover what’s going on. Perhaps it’s because you’re tracing a bug or are just curious about how jQuery achieves a particular UI

10 Mobile Cheat Sheets for Mobile Development10 Mobile Cheat Sheets for Mobile DevelopmentMar 05, 2025 am 12:43 AM

This post compiles helpful cheat sheets, reference guides, quick recipes, and code snippets for Android, Blackberry, and iPhone app development. No developer should be without them! Touch Gesture Reference Guide (PDF) A valuable resource for desig

See all articles

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)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools