여러 CSS / JS 파일 결합 및 축소
CSS 및 JS 파일을 통합하고 압축하여 사이트 성능을 최적화하려고합니다. 내 질문은 내가 직면 한 실제 상황을 감안할 때 이것을 달성하는 방법에 대한 (구체적인) 단계에 관한 것입니다 (하지만 다른 개발자들 사이에서도 전형적이어야 함).
내 페이지는 다음과 같은 여러 CSS 및 JS 파일을 참조합니다.
<!--
It's easier to work on smaller files during development.
Hence, the multiple CSS and JS files.
-->
<link type="text/css" rel="stylesheet" href="/css/main.css" />
<link type="text/css" rel="stylesheet" href="/css/secondary-1.css" />
<link type="text/css" rel="stylesheet" href="/css/secondary-2.css" />
<script type="text/javascript" src="/scripts/js/main.js"></script>
<script type="text/javascript" src="/scripts/js/adapter/adapter.js"></script>
<script type="text/javascript" src="/scripts/js/adapter/title-adapter.js"></script>
프로덕션 릴리스의 경우 3 개의 CSS 파일을 하나로 결합하고 예를 들어 YUI Compressor를 사용하여 축소하고 싶습니다 . 하지만 새로 축소 된 CSS를 참조하기 위해이 3 개의 파일이 필요한 모든 페이지를 업데이트해야합니다. 오류가 발생하기 쉬운 것 같습니다 (예 : 많은 파일에서 일부 줄을 제거하고 추가하는 경우). 덜 위험한 다른 접근 방식이 있습니까? JS 파일에 대해서도 동일한 문제입니다.
minify를 확인하십시오 -여러 js, css 파일을 URL에 쌓기 만하면 하나로 결합 할 수 있습니다.
<script src="/scripts/js/main.js,/scripts/js/adapter/adapter.js"></script>
우리는 수년 동안 그것을 사용해 왔으며 훌륭한 작업을 수행하고 즉시 수행합니다 (파일을 편집 할 필요 없음).
YUI Compressor 가 최고 라고 생각합니다 . JS와 CSS를 축소하고 console.log
사람들이 저수준 JavaScript 디버깅에 사용 하는 문을 제거합니다 .
ant 작업에서 시작할 수 있으므로 svn / git을 사용하는 경우 post / pre-commit 후크에 포함시킬 수 있습니다.
업데이트 : 요즘 나는 concat, minify & uglify 기여와 함께 grunt를 사용합니다. 감시자와 함께 사용할 수 있으므로 소스를 변경할 때마다 백그라운드에서 새로운 축소 된 파일을 생성합니다. uglify contrib는 콘솔 로그를 제거 할뿐만 아니라 사용하지 않는 기능과 속성도 제거합니다.
간략한 정보는 이 튜토리얼 을 참조하십시오 .
업데이트 : 요즘 사람들은 grunt와 그 전임자 "gulp"에서 물러나서 npm을 빌드 도구로 사용합니다. 여기 에서 읽어보십시오 .
업데이트 : 이제 사람들은 npm을 실행 하기 위해 yarn 을 사용 합니다. 당연합니다. 원사 아이콘은 고양이입니다. 대부분의 현재 프레임 워크는 웹팩 을 사용 하여 리소스를 패키지로 묶은 다음 축소도 처리 합니다.
I'd need to update all pages that needs these 3 files to reference to the newly-minified CSS.
Firstly I would say you should have common header. So it will needn't to change all headers at all time whenever necessary. It's good practice to have single header or 2-3. So as your page need you can change your header. So whenever you want to extend your web-app it will be less risky and tedious.
You havn't mentioned your development environments. You can see there are many compressing tools listed for different environments. And you are using good tool i.e.YUI Compressor.
I ended up using CodeKit to concatenate my CSS and JS files. The feature that I find really useful is the ability to do the concatenation upon file save; because it monitors the respective CSS / JS assets. Once I got them properly combined e.g. to 1 CSS and 1 JS files, all other files simply can refer to these 2.
You can even ask CodeKit to do on-the-fly minification / compression.
Disclaimer: I am not affiliated in any way with CodeKit. I randomly found it on the web and it has served as a great tool in my development process. It also comes with good updates since I first used it more than a year ago.
Quick tip for windows users, if you only want to concat files:
Open a cmd at the desired place, and just pipe your files to a file using "type"
ex:
type .\scripts\*.js >> .\combined.js
If the order of your scripts is important, you have to explicitly type the files, in the desired order.
I use this in a bat file for my angular/bootstrap projects
del combos.js
type .\lib\jquery.min.js >> .\combos.js
type .\lib\bootstrap.min.js >> .\combos.js
type .\lib\Angular\angular.min.js >> .\combos.js
type .\lib\Angular\angular-route.min.js >> .\combos.js
type .\lib\Angular\angular-sanitize.min.js >> .\combos.js
type .\app.js >> .\combos.js
type .\services\*.js >> .\combos.js
type .\controllers\*.js >> .\combos.js
It's 2015 year in the street and the easiest way imo is using gulp - http://gulpjs.com/. Minifying code using gulp-uglify for js scripts and gulp-minify-css for css is very simple. Gulp is definitely worth of trying
I dont see you mention a content management system (Wordpress, Joomla, Drupal, etc) but if you are using any popular CMS they all have plugins/modules available (free options as well) that will minify and cache your css and js.
Using a plugin gives you the ability to keep the uncompressed versions available for editing, then when changes are made the plugin automatically includes your changes and re compresses the file. Just make sure you choose a plugin that will let you exclude files (such as a custom js file) incase it breaks anything.
I have tried in the past to keep these files up manually and it always turns into a maintenance nightmare. Good luck, hope this helped.
For people who want something a little more lightweight and flexible, I created js.sh today to address this problem. It's a simple command line tool targeted toward JS files that could easily be modified to take care of CSS files too. Benefits:
- Easily configurable for use by multiple developers on a project
- Combines JS files in the order specified in script_order.txt
- Compresses them with Google's Closure Compiler
- Splits JS into <25kb chunks where possible since the iPhone won't cache anything greater than 25kb
- Generates a small PHP file with
<script>
tags that you can include where appropriate - Usage:
js.sh -u yourname
It could use some improvements, but it's better for my use case than all of the other solutions I've seen so far.
First step of optimization is file minimization. (I strongly recommend GULP for minimization and optimization. Its simple watch solution, installation and all files are compressed at once.Supports all CSS, JS,less, sass, etc...)
OR Old school solution:
1) In general, as a process of optimization, to optimize a site performance, try merging all CSS in one file and compress file by using Compass. That way your multiple requests to static CSS will be replaced with single one.
2) Problem of multiple JS you can resolve by using CDN (or Google Hosted Libraries) so requests go to other server not yours. That way server doesn't wait for previous request to complete before sending next.
3) If you have your own locally stored JavaScript minimize each file by using Brackets plugin "Compress JavaScript". It's basically one click to compress JavsScript.Brackets is free editor made for CSS and JS but can be used for PHP and other languages. There is plenty of plugins to choose made for both front-end and back-end developers. In general "one click" to do all these (so far multiple) commands. Btw, Brackets replaced my very expensive Dreamweaver ;)
3) Try using tools like Sass, Compass, less to minimize you CSS.
Note: Even without using SASS mixing or variables your CSS will be compressed (just simple use pure CSS and Compass "watch" command will compress it for you).
I hope this helps!
If you're doing any pre-processing on the files you serve, you probably want to set up a proper build system (eg a Makefile). That way, you have some source files with no duplication, and whenever you make a change, you run 'make' and it brings all the automatically-generated files up to date. If there is already a build system in place, learn how it works and use it. If not, you'll need to add one.
So first, figure out how to combine and minify your files from the command line (the YUICompressor documentation covers this). Designate a directory for automatically-generated stuff, separate from the stuff you work on but accessible to the web server, and output to there, eg gen/scripts/combined.js. Put the commands you used into a Makefile, and rerun 'make' every time you've made a change and want it to take effect. Then update the headers in other files to point to the combined and minified files.
In my symfony project I do something like this
{# layout.html.twig #}
{% block styles %}
{% if app.environment == 'prod' %}
<link href="{{ asset('bundles/appmain/min.css') }}" rel="stylesheet" type="text/css" />
{% else %}
<link href="{{ asset('bundles/appmain/hello.css') }}" rel="stylesheet" type="text/css" />
<link href="{{ asset('bundles/appmain/world.css') }}" rel="stylesheet" type="text/css" />
{% endif %}
{% endblock %}
{# some-view.html.twig #}
{% extends 'AppMainBundle::layout.html.twig' %}
{% block styles %}
{{ parent() }}
{% if app.environment != 'prod' %}
<link href="{{ asset('bundles/appsecond/styles.css') }}" rel="stylesheet" type="text/css" />
{% else %}
{% endblock %}
When the dev version is ready for production, I use this script to combine all css files and replace the contents of min.css
.
But this solution works only if the same css files are included in all pages.
You can use the cssmin node module which is built from the famous YUI compressor
$ npm -g i cosmic # install
# Usage
var puts = require('util').puts,
fs = require('fs'),
cssmin = require('./cssmin');
var css = fs.readFileSync("/Any/Random/CSS/File.css", encoding='utf8');
var min = cssmin(css);
puts(min);
All quicker utilities are found here
http://www.code-stuff.net
http://www.code-stuff.net/HttpUtility
http://www.code-stuff.net/HttpUtility/minifyCSS
http://www.code-stuff.net/HttpUtility/stringify_json
참고URL : https://stackoverflow.com/questions/9287823/combine-and-minify-multiple-css-js-files
'programing tip' 카테고리의 다른 글
프레임 워크에서 프레임 워크 없음으로 전환 (0) | 2020.09.08 |
---|---|
"바이트 수"를 0으로 설정하여 memcpy () 및 memmove ()를 호출 할 수 있습니까? (0) | 2020.09.08 |
명령 프롬프트는 종료 대기 시점을 어떻게 알 수 있습니까? (0) | 2020.09.08 |
약속 : 다음 대 다음 + 잡기 (0) | 2020.09.08 |
어셈블리 바인딩 리디렉션 : 방법 및 이유 (0) | 2020.09.08 |