Put javascript and css inline in a single minified

2020-06-09 03:51发布

问题:

A typical website consists of one index.html file and a bunch of javascript and css files. To improve the performance of the website, one can:

  • Minify the javascript and css files, to reduce the file sizes.
  • Concatenate the javascript files into one file and similar for the css files, to reduce the number of requests to the server. For commonly used (and shared) libraries like jquery it makes sense to leave them external, allowing the browser to cache the library and reuse it in different web applications.

I'm wondering if it makes sense to put the concatenated javascript and css file inline in on single html file, which will reduce the number of requests even further. Will this improve the performance of your site? Or will it work reversed, making it impossible for the browser to cache anything?

回答1:

Concatinating your CSS and JS files into one file will reduce the number of requests and make it load faster. But as commented, it won't make much sense unless you have a one-page site and the load time of that page is very critical. So you're better off to separate CSS from Javascript in my opinion.

Here's a book where you can learn more about the topic:

High Performance Web Sites



回答2:

this tools maybe help you. Turns your web page to a single HTML file with everything inlined - perfect for appcache manifests on mobile devices that you want to reduce those http requests.

https://github.com/remy/inliner



回答3:

This is not a good idea for the following reasons:

  1. You will not enjoy the benefit of cache

  2. You will load unneeded resources in all of your pages

  3. You will have a hard time while developing your website because of large files with unrelated code branches

  4. If you work in a team you will have to work with your teammates on the same files always, which means that you will have a lot of merge conflicts.



回答4:

It would cut down on the number of requests but it would also mean no caching of those for use on other pages. Think of defining an external file as also a way to tell the browser "and this section of the site is reusable". You'd be taking that ability away and so the CSS and JS would load. Like jackwanders said it's great if you only have one page.



回答5:

You can have a single CSS for all your pages and since it will be cached, the subsequent pages will refer it from cache without sending extra request.

However, putting all Javascript files is into one is contextual. Most probably you might be using libraries like jQuery, and relevant plugins. This 'might' throw conflicting issues between plugins. So, before you try it all at once, try merging few files at once and checking if the error pops or not.