简体   繁体   中英

Download css and js in one file (package)

I'm working on optimising a site and one of the biggest issues it has is that there are far too many resource requests.

JavaScript and CSS bundling and minification go a long way to improve this but they're somewhat at odds with transparent naming.

For example, if I have 3 widgets on my page that all have their own JS and CSS, I could bundle all the JS into one file and all the css into another file. this would reduce the round-trips from 6 to 2. However, the resulting bundle would be wasteful if another page only used one of those 3 widgets.

What I'd like to do is bundle all the JS AND CSS for a particular widget into a single file. The browser would then have to unpack this and make it available to the page. A logical extension to this would be to create a package of packages so that all the resource files for all the widgets were downloaded in a single file.

The only way I can think of doing this is with a web service and then writing the output directly to the document with JavaScript. This feels wrong as I don't think the browser would be cache this appropriately.

Any thoughts?


TL; DR

Has anyone come up with a way of packaging CSS and JS files into a single file to reduce round-trips to the server?

As somethinghere said , it is not a good idea to package both in a single file and send it to the client. A CSS cannot add JavaScript, but a JavaScript can be used to include CSS to the body. So the only way is to add the CSS as a single string variable and making document.createElement and appending it to the head .

If you are concerned about the HTTP requests, you can either embed the CSS fully inside the <head> or you can make use of Data URI Scheme. The downside of Data URI Scheme is that, the browsers IE 8 and below have less or no support.

Solution: It is a must and best to include three requests at a minimum, for:

  • The page itself
  • CSS Stylesheet
  • JavaScript Scripts

Other Solutions include adding the CSS and JavaScript contents directly inside the <head> or using the Data URI scheme.

Not sure but one hack is to create a html file and add your js and css in it and import that file in your original html file

something like this

<head>
   <link rel="import" href="library.html">
</head>

and your library will look like this

<html><script>YOUR JS code</script><style>YOUR STYLES</style></html>

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