我在我的网页应用程序中使用jQuery,并且需要将更多的jQuery脚本文件加载到单个页面中。
Google建议将所有的jQuery脚本文件合并为一个文件。
如何做到这一点?
我在我的网页应用程序中使用jQuery,并且需要将更多的jQuery脚本文件加载到单个页面中。
Google建议将所有的jQuery脚本文件合并为一个文件。
如何做到这一点?
在 Linux 上,你可以使用一个简单的 shell 脚本 https://github.com/dfsq/compressJS.sh 来将多个 JavaScript 文件合并成一个文件。它利用了 Closure Compiler 在线服务,因此生成的脚本也被有效压缩了。
$ ./compressJS.sh some-script.js another-sctipt.js onemore.js
尝试使用Google Closure编译器:
http://code.google.com/closure/compiler/docs/gettingstarted_ui.html
只需合并文本文件,然后使用类似YUI Compressor的工具进行压缩。
使用命令cat *.js > main.js
轻松地组合文件,然后可以通过java -jar yuicompressor-x.y.z.jar -o main.min.js main.js
运行main.js通过YUI压缩器进行压缩。
更新于2014年8月
我现在已经迁移到使用Gulp进行JavaScript串联和压缩,因为借助各种插件和一些最小化配置,您可以设置依赖性、编译Coffeescript等,并压缩JS。
您可以通过以下方式实现:
<script>
标签中即可。通常我会在Makefile
中设置它:
# All .js compiled into a single one.
compiled=./path/of/js/main.js
compile:
@find ./path/of/js -type f -name "*.js" | xargs cat > $(compiled)
make compile
$ mergejs js_files_list.txt output.js
如果您还想压缩合并后的文件:
$ mergejs -c js_files_list.txt output.js
output-min.js
。或者:$ mergejs -c js_files_list.txt output.js output.minified.js
output.minified.js
,我认为对于简单的网站非常有用。将此脚本复制到记事本中,另存为.vbs文件。 将.js文件拖放到此脚本上。
注: 仅适用于Windows操作系统。
set objArgs = Wscript.Arguments
set objFso = CreateObject("Scripting.FileSystemObject")
content = ""
'Iterate through all the arguments passed
for i = 0 to objArgs.count
on error resume next
'Try and treat the argument like a folder
Set folder = objFso.GetFolder(objArgs(i))
'If we get an error, we know it is a file
if err.number <> 0 then
'This is not a folder, treat as file
content = content & ReadFile(objArgs(i))
else
'No error? This is a folder, process accordingly
for each file in folder.Files
content = content & ReadFile(file.path)
next
end if
on error goto 0
next
'Get system Temp folder path
set tempFolderPath = objFso.GetSpecialFolder(2)
'Generate a random filename to use for a temporary file
strTempFileName = objFso.GetTempName
'Create temporary file in Temp folder
set objTempFile = tempFolderPath.CreateTextFile(strTempFileName)
'Write content from JavaScript files to temporary file
objTempFile.WriteLine(content)
objTempFile.Close
'Open temporary file in Notepad
set objShell = CreateObject("WScript.Shell")
objShell.Run("Notepad.exe " & tempFolderPath & "\" & strTempFileName)
function ReadFile(strFilePath)
'If file path ends with ".js", we know it is JavaScript file
if Right(strFilePath, 3) = ".js" then
set objFile = objFso.OpenTextFile(strFilePath, 1, false)
'Read entire contents of a JavaScript file and returns it as a string
ReadFile = objFile.ReadAll & vbNewLine
objFile.Close
else
'Return empty string
ReadFile = ""
end if
end function
脚本分组是适得其反的,你应该使用类似于http://yepnopejs.com/或http://headjs.com这样的工具并行加载它们。
npm install uglify-js -g
,然后执行uglifyjs file1.js file2.js -o output.js -c -m
。 - Praveen