Why separate vendor CSS & JS from custom CSS & JS in a workflow? - gruntjs

I've been trying to determine the reasoning behind what seems to have become the standard practice in Front End workflows of separating vendor JS & CSS from custom JS & CSS. I'm not sure what the benefits are over the disadvantage of an extra HTTP request, it would seem cleaner to just have a single CSS & JS file rather than having vendor.css, main.css & vendor.js, main.js.
Can anyone shed some light on this?

Vendor code typically changes less frequently than your application's code. Thus as you update your application, the vendor code can remain unchanged and cached in your user's browser.
In the scenario where vendor code is bundled with application code, the user has to download all of the vendor code every time you update the application.
The extra HTTP request from the separate vendor bundle is mitigated by the fact that the user will download less code on each application update.

I can think of two reasons.
Hosting vendor code separately from your code (e.g. Google Hosted Libraries)
Separation of concerns: the vendor code might be large and is updated independently of your custom code. Maintaining your code in a separate file avoids the need to put vendor code into your source control, makes it easier to navigate your code, makes it easy to upgrade to new vendor code since you know for certain the vendor code has not been tweaked.
Especially since you tagged the question with grunt, the end user might never see this change since you can merge vendor and user styles/scripts during the build.
However, if vendor code is large and changes infrequently, you do get a caching benefit from having a rarely changing, large vendor file accompanied by a small, fast changing custom code file. For large sites that do not use a CDN (hopefully, not yours), the impact can be noticeable.

Depending on your situation, this allows you to make your edits lower in the cascade so you can override vendor styles and behaviors without blowing away their code. This is helpful so that you always have a working version(vendor code) you can revert to. In situations like working with Wordpress, developing a child theme allows the parent theme to be updated without blowing away your customizations.

Various answers already addressed this but i'll make it very specific:
Vendor code might change more or less frequently than your code. If
vendor code changes more frequently, e.g. for bug fixes, you would
want to use the newer versions and have a better overall website.
If vendor code changes LESS frequently than your code, you may wish
to change your code w/o touching working stuff.
Vendor code is often hosted on CDNs, for example https://cdnjs.com/#q=ajax or
https://developers.google.com/speed/libraries/ These are FAST
loading. They also wont change, so the user can rely on cached
files and thus your website will load up faster.
It is generally better to make iterative changes to code. It is also easier to manage code, esp with source control when specific
things are changing. No need to swap large files when they have not
changed. Keeping things separate makes it easier to make
incremental changes, esp if the two things have different change
velocities.

Related

Remove unnecessary .js and .css calls (Rt-Theme19 - themeforest)

I have a ((very)) simple WP site with the above mentioned theme.
The theme loads a ton of external .css and .js files above the fold that causes render-blocking and I am sure I don't use half of them.
The header.php only includes a few directly and most are included via the php wp_head() -tag. I am struggling to find out, which .js and .css are in use and which aren't. Also how to get rid of them totally since I feel like using 'defer' or 'async' is only solving the problem partially.
My site is http://toptand.dk. Be aware, that I currently use WP Super cache for compressing and autooptimize to further minimize render-blocking etc. which might make the header look very different. I would rather get rid of it for real.
I have read many articles about how to prevent render-blocking, but non really explains how to deal with all the crap from a WP template.
The theme loads a ton of external .css and .js files above the fold
that causes render-blocking and I am sure I don't use half of them.
This is very typical of commercial WordPress themes; such themes load many files, as many are required for the "multipurpose" backend functions which provide short-codes, drag-and-drop features, custom post types, ecommerce, etc.
You sacrifice speed and page weight for all those features you use as well as the potential features you don't. If you need speed and a light-weight site, don't use a theme like that. You can go into that theme and wp_dequeue_script scripts and style sheets, but the features theme will break. See https://codex.wordpress.org/Function_Reference/wp_dequeue_script
Try a simpler, lighter weight (and free) theme from https://wordpress.org/themes/ and learn how themes work https://developer.wordpress.org/themes/getting-started/ in order to get features you want without all the extra code.
You can utilize Chrome Dev Tools' Audits tab.
I am struggling to find out, which .js and .css are in use and which
aren't
Upon selecting the Audits tab, include Network Utilization based on necessity but mandatorily check Web Page Performance option. Once the selection is done, either click on Audit Present State or Reload and audit.
Once the process is complete, the results will provide inputs on the number of unused CSS rules. This will give you an idea about the unused CSS.
Also how to get rid of them totally since I feel like using 'defer' or
'async' is only solving the problem partially.
The recent version of Chrome (59) has brought in a new feature called Coverage (you can find this under More Tools inside the dev tools). This helps in understanding the percentage of the CSS being used in the current page and clicking on one of the results redirects to the code and marks the portions of non-executed code in red and the executed ones in green.
These inputs should help you optimize your assets and remove the unused code.
Hope this helps!

Bundling and Minification dynamically

I have a question about bundling. Think about a situation like this. Take jquery DataTables for example. It has few plugins that you can use as and when you need them. In some pages, just using the base script files will do the job. but in another page, I might need to use Fixed Header plugin, in another page I might need to use Fixed Header plugin as well as Table Tools plugin.
What is the best way to approach these kind of situations in bundling. Should I create just one bundle which include all of the script files (even the ones that I might not use in some pages but in others) or create bundles specifically to each page or is there a better way of doing this. I'd like to be able to do something like
Scripts.Render("~/bundles/datatables", "FixedHeader", "TableTools")
which will include the relevant files and minify them.
Any help really appreciated.
Thanks,
Amila
Part of this, no one can answer for you. Bundling is always a trade-off: you're reducing requests at the cost of a larger file that has to be downloaded. You'll personally have to weigh the additional weight added by those scripts in the initial request versus the time it will take to request them later.
As a general guideline, this will mostly be about your audience. Do you expect a high number of mobile users? At least in the U.S., mobile data is expensive and fairly limited (because of the outrageous cost, people try to choose the lowest data tiers possible). Forcing your mobile users to download a large JS file which includes code that may never be run, is a waste of their data. While, if your target will be desktop users, a big file is no problem and is in fact preferable, as there's no concerns typically over data usage and the page load times for other pages will be improved. Even with mobile, though, sometimes users prefer faster page loads over less data usage, so even that has to be judged.
That said, if you don't choose to bundle them all together from the start, you can actually create bundles on the fly.
#{ BundleTable.Bundles.Add(new ScriptBundle("~/bundles/onthefly").Include("~/Path/To/Some/Script.js")); }
And then, as usual:
#Scripts.Render("~/bundles/onthefly")
Please take a look at the Enfold project. It might be able to accomplish what you need.
Assuming you have the following views in the web project:
~/Views/Home/About.cshtml
~/Views/Home/Contact.cshtml
~/Views/Home/Index.cshtml
You can organize your Javascript files this way:
~/Scripts/Views/default.js
~/Scripts/Views/Home/default.js
~/Scripts/Views/Home/about.js
~/Scripts/Views/Home/contact.js
~/Scripts/Views/Home/index.js
With such a setup, the following bundles will be created:
~/bundles/home/about
~/scripts/views/default.js
~/scripts/views/home/default.js
~/scripts/views/home/about.js
~/bundles/home/contact
~/scripts/views/default.js
~/scripts/views/home/default.js
~/scripts/views/home/contact.js
~/bundles/home/index
~/scripts/views/default.js
~/scripts/views/home/default.js
~/scripts/views/home/index.js

Combining CSS files: per site or per page template?

We all know that we're supposed to combine our CSS into one file, but per site or per page? I've found pro's and cons to both.
Here's the scenario:
Large site
CSS files broken out into one file for global styles and many for modules
Solution A: Combine ALL the CSS files for the whole site into one file:
Best part is that the one file would be cached on every page after the initial hit! The downside is that naming convention for your selectors (classes and id's) becomes more important as the chance for a namespace collision increases. You also need a system for styling the same module differently on separate pages. This leads to extra selectors in your CSS which is more work for the browser. This can cause problems on mobile devices like the iPad that don't have as much memory and processing power. If you're using media queries for responsive design, you're troubles compound even further as you add in the extra styles.
Solution B: Combine one CSS file per page template:
(By page template I mean one layout, but many different pages, like an article page)
In this scenario, you lose most of the issues with selecting described above, but you also lose some of the cache advantages. The worst part of this technique is that if you have the same styles on 2 different page templates then they'll be download twice, once for each page! For instance, this would happen with all your global files. :(
Summary:
So, as is common in programming, neither solution is perfect, but if anyone has run into this and found an answer I'd love to hear it! Especially, if you know of any techniques that help with the selector issue of Solution A.
Of course, combine and minify all the global styles, like your site template, typography, forms, etc. I would also consider combining the most important and most frequently used module styles into the global stylesheet, certainly the ones that you plan to use on the home page or entry point.
Solution B isn't a good one: the user ends up downloading the same content for each unique layout/page when you could have just loaded parts of it from the last page's cache. There is no advantage whatsoever to this method.
For the rest, I would leave them separate (and minified) and just load them individually as needed. You can use any of the preloading techniques described on the Yahoo! Developer network's "Best Practices for Speeding Up Your Web Site" guide to load the user's cache beforehand:
Preload Components
By preloading components you can take advantage
of the time the browser is idle and request components (like images,
styles and scripts) you'll need in the future. This way when the user
visits the next page, you could have most of the components already in
the cache and your page will load much faster for the user. There are actually several types of preloading:
Unconditional preload - as soon as onload fires, you go ahead and fetch some extra components. Check google.com for an example of how a
sprite image is requested onload. This sprite image is not needed on
the google.com homepage, but it is needed on the consecutive search
result page.
Conditional preload - based on a user action you make an educated guess where the user is headed next and preload accordingly. On
search.yahoo.com you can see how some extra components are requested
after you start typing in the input box.
As far as the conflicting selectors go: combining all the files and doing it any other way should not make a difference, this is a problem with your design. If possible, have all modules "namespaced" somehow, perhaps by using a common prefix for classes specific to the module, like blog-header or storefront-title. There is a concept called "Object-oriented CSS" that might reduce the need for lots of redundant CSS and module-specific class names, but this is normally done during the design phase, not something you can "tack on" to an existing project.
Less HTTP requests is better, but you have to take file size into consideration as well as user behavior and activity. The initial download time of the entry page is the most important thing, so you don't want to bog it down with stuff you won't use until later. If you really want to crunch the numbers, try a few different things and profile your site with Firebug or Chrome's developer tools.
i think you can make global.css that store style that need every template.
And you could make css in each template.
Or simply use css framework like lescss

CSS Version Control Idea

I had an idea for "cheap" version control of the css of one of my sites, but am thinking it may not be a good idea. Thought I'd throw it out here in case someone has a similar idea that works better (besides real svn, etc.)
My thought was to create a main css file like "sitename.css" then use #import inside this file to connect to the most recent file with updates. I'd name these imported files by date, eg: 20101222_css.css so I'd know when the last update was applied. When I have a change, I could make my edits, drop the update in the respective location, change the #import to the new file, and viola... updated on the site.
After reading about issues with #import, such as it loading AFTER the page finishes, I'm not too keen on this now.
Any ideas of a way to implement something similar without a full blown system? I do a lot of small project work for various people and thought this method may be a simple way to keep track of things.
Thanks for any ideas/suggestions.
Your idea would add additional page loads to your site for no good reason, which will be a performance hit. It would also expose your versioning to the outside world. And as you say it will suffer from slow loading speeds due to the way #import works.
But the real down-side of this technique is that it only works for CSS files. You haven't solved the problem for any other files on your site.
You seem to think it would be simpler to use than a real SVN setup, but if you end up coming up with different techniques like this for every type of file on your site, you could easily end up giving yourself more headaches than you solve.
SVN is actually quite straightforward to use. With a good GUI (try TortoiseSVN), it's so easy you almost forget its there. Seriously, use SVN. There's no need to come up with 'clever' alternatives.
Its not a good idea, especially if you push this into production. If you want "cheap" version control, download VisualSVN. Its free.
The guys at Yahoo use a technique that reminds me of what you describe:
<link rel="stylesheet" type="text/css" href="http://l.yimg.com/a/combo?arc/yui/reset_2.6.7.css&arc/yui/fonts_2.6.4.css&[....]/subfooter_0.0.12.css" />
It makes sense for them because it's a caching tecnique. They set HTTP headers so stuff never expires: if you load the site one year later and you haven't removed your browser's cache, you shouldn't need to fetch again any of the files that haven't changed.
However, it's by no means a sensible version control system. You already have a good bunch of real version control systems out there!

Single huge .css file vs. multiple smaller specific .css files? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
Is there any advantage to having a single monster .css file that contains style elements that will be used on almost every page?
I'm thinking that for ease of management, I'd like to pull out different types of CSS into a few files, and include every file in my main <link /> is that bad?
I'm thinking this is better
positions.css
buttons.css
tables.css
copy.css
vs.
site.css
Have you seen any gotchas with doing it one way vs. the other?
This is a hard one to answer. Both options have their pros and cons in my opinion.
I personally don't love reading through a single HUGE CSS file, and maintaining it is very difficult. On the other hand, splitting it out causes extra http requests which could potentially slow things down.
My opinion would be one of two things.
1) If you know that your CSS will NEVER change once you've built it, I'd build multiple CSS files in the development stage (for readability), and then manually combine them before going live (to reduce http requests)
2) If you know that you're going to change your CSS once in a while, and need to keep it readable, I would build separate files and use code (providing you're using some sort of programming language) to combine them at runtime build time (runtime minification/combination is a resource pig).
With either option I would highly recommend caching on the client side in order to further reduce http requests.
EDIT:
I found this blog that shows how to combine CSS at runtime using nothing but code. Worth taking a look at (though I haven't tested it myself yet).
EDIT 2:
I've settled on using separate files in my design time, and a build process to minify and combine. This way I can have separate (manageable) css while I develop and a proper monolithic minified file at runtime. And I still have my static files and less system overhead because I'm not doing compression/minification at runtime.
note: for you shoppers out there, I highly suggest using bundler as part of your build process. Whether you're building from within your IDE, or from a build script, bundler can be executed on Windows via the included exe or can be run on any machine that is already running node.js.
A CSS compiler like Sass or LESS is a great way to go. That way you'll be able to deliver a single, minimised CSS file for the site (which will be far smaller and faster than a normal single CSS source file), while maintaining the nicest development environment, with everything neatly split into components.
Sass and LESS have the added advantage of variables, nesting and other ways to make CSS easier to write and maintain. Highly, highly recommended. I personally use Sass (SCSS syntax) now, but used LESS previously. Both are great, with similar benefits. Once you've written CSS with a compiler, it's unlikely you'd want to do without one.
http://lesscss.org
http://sass-lang.com
If you don't want to mess around with Ruby, this LESS compiler for Mac is great:
http://incident57.com/less/
Or you could use CodeKit (by the same guys):
http://incident57.com/codekit/
WinLess is a Windows GUI for comipiling LESS
http://winless.org/
I prefer multiple CSS files during development. Management and debugging is much easier that way. However, I suggest that come deployment time you instead use a CSS minify tool like YUI Compressor which will merge your CSS files into one monolithic file.
Historically, one of the main advantages x in having a single CSS file is the speed benefit when using HTTP1.1.
However, as of March 2018 over 80% of browsers now support HTTP2 which allows the browser to download multiple resources simultaneously as well as being able to push resources pre-emptively. Having a single CSS file for all pages means a larger than necessary file size. With proper design, I don't see any advantage in doing this other than its easier to code.
The ideal design for HTTP2 for best performance would be:
Have a core CSS file which contains common styles used across all pages.
Have page specific CSS in a separate file
Use HTTP2 push CSS to minimise wait time (a cookie can be used to prevent repeated pushes)
Optionally separate above the fold CSS and push this first and load the remaining CSS later (useful for low-bandwidth mobile devices)
You could also load remaining CSS for the site or specific pages after the page has loaded if you want to speed up future page loads.
You want both worlds.
You want multiple CSS files because your sanity is a terrible thing to waste.
At the same time, it's better to have a single, large file.
The solution is to have some mechanism that combines the multiple files in to a single file.
One example is something like
<link rel="stylesheet" type="text/css" href="allcss.php?files=positions.css,buttons.css,copy.css" />
Then, the allcss.php script handles concatenating the files and delivering them.
Ideally, the script would check the mod dates on all the files, creates a new composite if any of them changes, then returns that composite, and then checks against the If-Modified HTTP headers so as to not send redundant CSS.
This gives you the best of both worlds. Works great for JS as well.
Having only one CSS file is better for the loading-time of your pages, as it means less HTTP requests.
Having several little CSS files means development is easier (at least, I think so : having one CSS file per module of your application makes things easier).
So, there are good reasons in both cases...
A solution that would allow you to get the best of both ideas would be :
To develop using several small CSS files
i.e. easier to develop
To have a build process for your application, that "combines" those files into one
That build process could also minify that big file, btw
It obviously means that your application must have some configuration stuff that allows it to swith from "multi-files mode" to "mono-file mode".
And to use, in production, only the big file
i.e. faster loading pages
There are also some software that do that combining of CSS files at run-time, and not at build-time ; but doing it at run-time means eating a bit more CPU (and obvisouly requires some caching mecanism, to not re-generate the big file too often)
Monolithic stylesheets do offer a lot of benefits (which are described in the other answers), however depending on the overall size of the stylesheet document you could run into problems in IE. IE has a limitation with how many selectors it will read from a single file. The limit is 4096 selectors. If you're monolithic stylesheet will have more than this you will want to split it. This limitation only rears it's ugly head in IE.
This is for all versions of IE.
See Ross Bruniges Blog and MSDN AddRule page.
There is a tipping point at which it's beneficial to have more than one css file.
A site with 1M+ pages, which the average user is likely to only ever see say 5 of, might have a stylesheet of immense proportions, so trying to save the overhead of a single additional request per page load by having a massive initial download is false economy.
Stretch the argument to the extreme limit - it's like suggesting that there should be one large stylesheet maintained for the entire web. Clearly nonsensical.
The tipping point will be different for each site though so there's no hard and fast rule. It will depend upon the quantity of unique css per page, the number of pages, and the number of pages the average user is likely to routinely encounter while using the site.
I typically have a handful of CSS files:
a "global" css file for resets and global styles
"module" specific css files for pages that are logically grouped (maybe every page in a checkout wizard or something)
"page" specific css files for overrides on the page (or, put this in a block on the individual page)
I am not really too concerned with multiple page requests for CSS files. Most people have decent bandwidth and I'm sure there are other optimizations that would have a far greater impact than combining all styles into one monolitic CSS file. The trade-off is between speed and maintainability, and I always lean towards maintainability. The YUI comperssor sounds pretty cool though, I might have to check that out.
I prefer multiple CSS files. That way it is easier to swap "skins" in and out as you desire. The problem with one monolithic file is that it can get out of control and hard to manage. What if you want blue backgrounds but don't want the buttons to change? Just alter your backgrounds file. Etc.
Maybe take a look at compass, which is an open source CSS authoring framework.
It's based on Sass so it supports cool things like variables, nesting, mixins and imports. Especially imports are useful if you want to keep seperate smaller CSS files but have them combined into 1 automatically (avoiding multiple slow HTTP calls).
Compass adds to this a big set of pre-defined mixins that are easy for handling cross-browser stuff.
It's written in Ruby but it can easily be used with any system....
here is the best way:
create a general css file with all shared code
insert all specific page css code into the same page, on the tag or using the attribute style="" for each page
on this way you have only one css with all shared code and an html page.
by the way (and i know that this is not the right topic) you can also encode your images in base64 (but you can also do it with your js and css files). in this way you reduce even more http requests to 1.
SASS and LESS make this all really a moot point. The developer can set up effective component files and on compile combine them all. In SASS you can toggle off the Compressed Mode while in development for easier reading, and toggle it back on for production.
http://sass-lang.com
http://lesscss.org
In the end a single minified CSS file is what you want regardless of the technique you use. Less CSS, Less HTTP requests, Less Demand on the server.
The advantage to a single CSS file is transfer efficiency. Each HTTP request means a HTTP header response for each file requested, and that takes bandwidth.
I serve my CSS as a PHP file with the "text/css" mime type in the HTTP header. This way I can have multiple CSS files on the server side and use PHP includes to push them into a single file when requested by the user. Every modern browser receives the .php file with the CSS code and processes it as a .css file.
You can just use one css file for performance and then comment out sections like this:
/******** Header ************/
//some css here
/******* End Header *********/
/******** Footer ************/
//some css here
/******* End Footer *********/
etc
I'm using Jammit to deal with my css files and use many different files for readability.
Jammit doest all the dirty work of combining and compressing the files before deployment in production.
This way, I've got many files in development but only one file in production.
A bundled stylesheet may save page load performance but the more styles there are the slower the browser renders animations on the page you are on. This is caused by the huge amount of unused styles that may not be on the page you are on but the browser still has to calculate.
See: https://benfrain.com/css-performance-revisited-selectors-bloat-expensive-styles/
Bundled stylesheets advantages:
- page load performance
Bundled stylesheets disadvantages:
- slower behaviour, which can cause choppyness during scrolling, interactivity, animation,
Conclusion:
To solve both problems, for production the ideal solution is to bundle all the css into one file to save on http requests, but use javascript to extract from that file, the css for the page you are on and update the head with it.
To know which shared components are needed per page, and to reduce complexity, it would be nice to have declared all the components this particular page uses - for example:
<style href="global.css" rel="stylesheet"/>
<body data-shared-css-components="x,y,z">
I've created a systematic approach to CSS development. This way I can utilize a standard that never changes. First I started with the 960 grid system. Then I created single lines of css for basic layouts, margins, padding, fonts and sizes. I then string them together as needed. This allows me to keep a consistent layout across all of my projects and utilize the same css files over and over. Because they are not specific. Here's an example: ----div class="c12 bg0 m10 p5 white fl"/div--- This means that the container is 12 columns across, utilizes bg0 has margins of 10px padding of 5 the text is white and it floats left. I could easily change this by removing or adding a new - What I call a "light" style- Instead of creating a single class with all these attributes; I simply combine the single styles as I code the page. This allows me to create any combination of styles and does not limit my creativity or cause me to create a massive number of styles that are similar. Your style sheets become a lot more manageable, minimized and allow you to re-use it over and over. This method I have found to be fantastic for rapid design. I also no longer design first in PSD but in the browser which also saves time. In addition because I have also created a naming system for my backgrounds and page design attributes I simply change out my image file when creating a new project.(bg0 = body background according to my naming system) That means that if I previously had a white background with one project simply changing it to black simply means that on the next project bg0 will be a black background or another image..... I have not found anything wrong with this method yet and it seems to work very well.

Resources