


Summary 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
Look at the source code of
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文件:
所有在红线边框里面的脚本文件都是由RequireJS自动加载的。
我们将用RequireJS Optimizer(RequireJS优化器)来优化这个项目。根据已下载的说明文件,找到r.js并将其复制到
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" })
我认为构建一个配置文件比在命令行中使用参数的可读性更高,因此我将采用这种方式。接下来我们就为项目创建一个
({ 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:
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
Run the optimizer
$ node r.js -o build.js
A new folder will be generated:
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.
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

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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

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

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

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

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

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.

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

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.
