简体   繁体   中英

All Javascript in one file compressed or multiple files

I am compressing all of my files on the go, so it's easier to update rather than having to decompress. I have around 10 JS files, in total around 2,000 lines maybe more, would it be better to put them all in one file and compress it, would it speed up my website, or should I just leave it in individual files, and compress each?

I'm assuming this is for web development.

If all of your scripts were created by you, and you suspect each script will be needed for every page on your site, you should concat / compress them. The first load will take longer, but the scripts will be cached.

If all of your scripts were authored by you, but each page does not necessarily need all 10 of your scripts, you should consider lazy loading them on demand.

If any of those scripts were not authored by you and can be found on a CDN (like jQuery), then link the scripts to a CDN, as there is a chance users will already have them cached. For the remaining scripts, decide if you should lazy load or concat / compress them all.

What you shouldn't do, however, is load all 10 of your scripts individually on each page. That would just have the user's browser send more requests than needed.

It's all about trade-offs, and there isn't a 100% correct answer. Good luck :)

--edit--

You said "on the go". If the content of your scripts change, then you wouldn't want them to be cached. In that case, lazy-loading would probably be the answer.

--edit 2--

If you haven't already, you should really take a look at using Grunt to concat and minify your js files during development. If you decide to go that route, take a look at grunt-contrib-watch .

It is often a good idea to keep the number of files the browser needs to request to a minimum.

The browser may have to open one connection per HTTP request, but if you put all your JavaScript code in one big file it will only have to do one request and thus only one connection needs to be opened to fetch your js code.

It depends on how much of that 2000 lines you are using for different pages. If the file is like a library of which most is used in your distinct pages, then it might actually make little to no difference in terms of loading speed. But if only a part of that file is being used in each page, I would assume separating would be smart as less will be needed to load per page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM