Package and compress seajs code

Source: Internet
Author: User
Background seajs is an excellent module development plug-in. However, when we use it for modular development, an http request will be made for loading each of its modules, when the number of modules increases, the page loading speed will be slowed down. To speed up the page background, seajs is an excellent module development plug-in, but when we use it for modular development, since each module is loaded with an http request, when the number of modules doubles, the page loading speed will be slowed down. In order to speed up page loading, we usually compress js and package the associated modules into an independent js file, this can greatly reduce the js file size and the number of http requests, which can increase the page loading speed. We can use spm to package and compress js files (using spm-build ), however, when we write JavaScript that is compatible with multiple environments (it can be referenced either directly using script or using seajs ), therefore, we cannot use the preceding method to package and compress js. The second step is to use spm-build to understand the package first. json file configuration is a little complicated. To reduce the difficulty and simplify functions, we will introduce the alternative use of nodejs to compress js scripts. Implementation http://tool.css-js.com/ The site provides a variety of script compression. By using YUI compression, we found that it actually uses http POST for code compression. Then we use ajax for testing. The Code is as follows: $. post (' http://tool.css-js.com/ ! Java /? Type = js & munge = true & preserveAllSemiColons = false & disableOptimizations = false', {code: 'var x = (function () {var foo = 1, bar = 2; return (foo + bar)} () '}, function (res) {console. log (res) ;}); the results are the same, next, we use nodejs to write a file for reading js files, initiate http, and splice the compressed file into an independent js file. Use the native nodejs http to initiate the post code as follows: var m_http = require ('http'); var m_qs = require ('querystring'); var options = {host: 'tool.css -js.com ', port: 80, method: 'post', path :'/! Java /? Type = js & munge = true & preserveAllSemiColons = false & disableOptimizations = false', headers: {'content-type': 'application/x-www-form-urlencoded '}}; exports. compress = function (str, callback) {var req = m_http.request (options, function (res) {res. setEncoding ('utf-8'); var compressed = ''; res. on ('data', function (chunk) {compressed + = chunk;}); res. on ('end', function () {callback (compressed)}) ;}); req. write (m_qs.st Ringify ({code: str}); req. end () ;}; with the compression method, we need to provide a function that can read all js files in the folder cyclically and compress them into independent js files, the code is roughly as follows: var m_fs = require ('fs'); var m_path = require ('path'); // other code is omitted exports. combineDir = function (dir, output) {var self = this; m_fs.readdirSync (dir ). forEach (function (filename) {if (filename. indexOf ('. ') =-1) {self. compressDir (m_path.join (dir, filename); return;} var path = m_path.join (dir, filename); m _ Fs. readFile (path, 'utf8', function (err, content) {if (err) {return;} self. compress (content, function (compressed) {var id = filename. substr (0, filename. indexOf ('. '); compressed = compressed. replace ('this. define (', ['this. define (\ '', id, '\', ']. join (''); m_fs.appendFileSync (output, compressed) ;};}) ;};}; the above Code should replace 'this. the define 'string is written because the closure is used to include the script internally in the compatible script. define to determine when this. define To assign the encoding module to the module. the example code is as follows: //. js (function () {var a = (function () {var foo = 1, bar = 2; return (foo + bar)} () if (this. define) {this. define (function (require, exports, module) {'require: nomunge, exports: nomunge, module: nomunge '; module. exports = ;});}}). call (this); // B. js (function () {var B = (function () {var foo = 1, bar = 2; return (foo + bar)} () if (this. define) {this. define (func Tion (require, exports, module) {'require: nomunge, exports: nomunge, module: nomunge '; module. exports = ;});}}). call (this); after merging using the encoded function, the result is as follows: (function () {var B = (function () {var c = 1, a = 2; return (c + a)} (); if (this. define) {this. define ('A', function (require, exports, module) {module. exports = B })}}). call (this); (function () {var c = (function () {var d = 1, B = 2; return (d + B )}()); if (this. define) {this. define ('B', function (requ Ire, exports, module) {module. exports = })}}). call (this); extended for request creation, we can use nodegrass to complete our functions. It encapsulates the http and https get and post functions internally, simplifying the call, you can use it. Second, when multiple layers of nested js files exist in the cyclic folder, the parent folder is not added to the id defined by seajs. Therefore, when the merged js file is called, errors may occur. Here we will not explain in detail how to solve the problem, so we will leave it to everyone. The asynchronous method is used for the above Code, resulting in multi-layer file nesting. If you think that too many nesting causes the code to be difficult to read, you can use wind. js or eventproxy. js or other asynchronous js to solve the problem of multi-layer nesting. This is the end of this Article. If you have any questions, please kindly advise. Thank you!
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.