Comparison of Loading CSS Inline, Embedded and from External Files

Comparison of loading CSS inline, embedded and from external files

It's all about where in the pipeline you need the CSS as I see it.

1. inline css

Pros: Great for quick fixes/prototyping and simple tests without having to swap back and forth between the .css document and the actual HTML file.

Pros: Many email clients do NOT allow the use of external .css referencing because of possible spam/abuse. Embedding might help.

Cons: Fills up HTML space/takes bandwidth, not resuable accross pages - not even IFRAMES.

2. embedded css

Pros: Same as above regarding prototype, but easier to cut out of the final prototype and put into an external file when templates are done.

Cons: Some email clients do not allow styles in the [head] as the head-tags are removed by most webmail clients.

3. external css

Pros: Easy to maintain and reuse across websites with more than 1 page.

Pros: Cacheable = less bandwidth = faster page rendering after second page load

Pros: External files including .css can be hosted on CDN's and thereby making less requests the the firewall/webserver hosting the HTML pages (if on different hosts).

Pros: Compilable, you could automatically remove all of the unused space from the final build, just as jQuery has a developer version and a compressed version = faster download = faster user experience + less bandwidth use = faster internet! (we like!!!)

Cons: Normally removed from HTML mails = messy HTML layout.

Cons: Makes an extra HTTP request per file = more resources used in the Firewalls/routers.

I hope you could use some of this?

Inline HTML vs external CSS efficiency/Best practices

External css classes make significant difference in the page load time as compared to inline css. When a html page is repeatdly loading by the user , external css files will be cached on browser thus loading becomes faster, as in the case of inline styles it need to be load each time

External CSS vs inline style performance difference?

The performance boost that your friend mentioned is probably too trivial compared to the amount of performance boost (through other factors) using a CSS file.

Using the style attribute, the browser only paints the rule for that particular element, which in this case is the <div> element. This reduces the amount of look up time for the CSS engine to find which elements match the CSS selector (e.g. a.hover or #someContainer li).

However, putting styling at element level would mean that you cannot cache the CSS style rules separately. Usually putting styles in CSS files would allow the caching to be done, thus reducing the amount of load from the server each time you load a page.

Putting style rules at the element level will also make you lose track of what elements are styled what way. It might also backfire the performance boost of painting a particular element where you can repaint multiple elements together. Using CSS files separates the CSS from HTML, and thus allows you to make sure that your styles are correct and it's easier to modify later on.

Therefore if you look at the comparison, you would see that using a CSS file has much more benefit than styling at element level.

Not to forget when you have an external CSS stylesheet file, your browser can cache the file which increases your application efficiency!

CSS: Is inline styling slower?

In terms of actually displaying content, the speed differences between the two sections of code is negligible. Different browsers most likely have different implementations for rendering a webpage so the minute speed boost you get with one browser won't necessarily be reflected in another.

Now in terms of load times, it's a different story. Yes, inline styles are technically faster than an external stylesheet because you are making one less request on top of the page but using an external stylesheet is much preferred for code maintainability. It's only when you're loading multiple stylesheets that performance starts to become an issue since each time you refer to an new stylesheet the browser must submit another request. The solution? Simply concatenate stylesheets together into one.

Where is the best place to put external css files (performance-wise)?

How to Maximize Rendering of a Web Page in Web Browsers

I must warn you, that CSS is not an issue at all when it comes to slow website rendering. Small CSS text files download extremely fast. There is very little you can change in CSS design today that will have much of an impact on that simply because most external CSS files are teeny-tiny compared to other downloaded resources. The main killer of performance are HUGE JavaScript API Libraries, slow web servers, and poor connection speeds on the user's end. But some tricks you can use are listed below, though I do not recommend you hijack your user's browsers to gain a few 100 milliseconds like this:

  1. Create a single external style sheet with just the exact amount of styles needed to render your homepage, or first-visit page in your site. Move all secondary CSS to a separate page (see below). This is your "synchronized" CSS that will load prior to the HTML download, parse, and rendering of the DOM. Link to this file using a simple <link> tag. If this is a small footprint, and you have removed all other CSS, it reduces the wait time for HTML to download, parse, render, and paint of the DOM tree. This external CSS sheet is cached over long periods of time, so it also loads lightning fast each return visit by your users unlike the embedded CSS used by many JavaScript API projects (Google Angular, for example) that must be reloaded each browser refresh. Note: Because of the new HTTP/2 protocol used by newer web servers, increased browser connections by modern HTML5 browsers, parallel CSS downloading, and faster networks, slow CSS speeds are almost a non-issue today.
<link media="screen" rel="stylesheet" type="text/css" href="css/homepage.css" />

  1. Set all unnecessary JavaScript external files to use "defer" when downloading. This means they will load in order but in parallel to other files over shared connections and not interfere with web page, CSS download, and HTML parsing. They will not run until all HTML and the DOM is rendered and painted, as well:
<script src="myscript.js" type="text/javascript" defer="defer"></script>

As an option, consider setting all external or global JavaScript files that affect all pages in your website, but which ARE required to draw the DOM, such that they download "asynchronously". Like "defer", these files will not stop HTML from rendering but as soon as these asynchronous files appear, they could block rendering of the page. Avoid this code unless these script files are mandatory to the rendering of the DOM and very small. In the old days we dropped these external script links at the bottom of the web page after the last HTML inside the body element. This way they only started downloading after the HTML was downloaded. But this async feature when supported may speed that process up slightly. Be sure to do Windows.load or other tricks to verify the page is rendered before running your async scripts.

<script type="text/javascript" src="myscript.js" async="async"></script>

  1. All the other CSS you don't need to render in the homepage, but which can load after the DOM, set them to "preload". However, the attribute preload in the <link> tag is not 100% supported yet in modern browsers and in none of the older ones (pre-HTML5). So, use this "print" trick below instead to get the browser to download these CSS external files via a "queue", which often means they download last in the order of resources and after the DOM is already rendered. This "print" media type trick has very wide browser support. Browsers have been doing this with media=print linked style sheets for 20+ years naturally, so this is just a "hack" to force regular sheets to use that model. After these are downloaded, all the other pages will use them, including your homepage and its scripts, if needed:
<link rel="stylesheet" href="styles.css" media="print" type="text/css" onload="this.media='screen';this.onload=null;" />

  1. Make sure your server uses HTTP/2 which comes with multiplexing. Its just a silly term that means downloaded files from browsers can now connect and download over a single connection, if needed, and in parallel. But that rarely is needed in modern browsers over fast network connections today unless you have lots and lots of scripts and media files in your page that are required for download. If you do, I would question the design of your website.

  2. There is a number of prefetch, prerender, preconnect, and other <link> tricks you can add, though in most cases they won't give you huge speed gains as most servers and browsers negotiate all these connections quite fast. Many of these connections are already cached by host providers, etc. These might come into play for poor countries with cell phone users who's devices must negotiate uncached DNS over distant Western servers. But here are some "tricks":

Add DNS prefetch calls below to external URL's or websites your page requires to access content quickly. These will fire calls to uncached DNS routes and prepare those connections for the browser to use. Only do this if you are accessing resources from foreign servers your page depends upon:

<link rel="dns-prefetch" href="//somewebsite.com" />

Add preconnect calls below to external URL's or websites your page requires to access content quickly. This works the same as above but for the actual URL's and their IP's, which often are cached already in your network:

<link rel="preconnect" href="//somewebsite.com" />

Add resource prefetch call below to assets in other pages you hope users will access AFTER they visit your homepage. These files will be cached, but implementation of the call is optional for the browser. This assume your users will access these resources after clicking through the site, which often is not true. So I would avoid this. Note: Browser support of this feature is limited.

<link rel="prefetch" href="someresource.jpg" />

Add resource prerender call below to web pages and all their associated resources you hope users will access after the viewing the current web page. These files will be cached, but implementation of the call is optional for the browser. As above, you need to assume a user will navigate to these cached pages. Also, "prerender" not only downloads the pages and resources, but builds the DOM, runs the JavaScript, and then switches out the page when the user clicks the link. This means you'e asking the browser for more CPU and thats wasteful for a page the user may never visit. This only works right in modern Chrome browsers, I believe. Note: Browser support of this feature is very limited.

<link rel="prerender" href="somewebpage.html" />

  1. Give all your images, iframes, video, and other HTML media elements a width and height attribute so the browser can reserve space in the painted browser canvas for these images while it downloads those items. This mainly prevent a shift in the layout but can give you speed if the browser does several paints.

  2. Give all your <img> elements a loading="lazy" attribute, which means they do not load till the user scrolls down the web page. This only works in modern HTML 5 browsers.

  3. Give all your <video>, <audio>, etc. a preload="metadata" attribute, which means they do not load and play till the user scrolls down the web page. This only works in modern HTML 5 browsers.

Keep in mind, most of these hacks and tricks for CSS and other things are rarely the culprit in slow sites. CSS has only recently gotten a bad rap when it comes to browser rendering speed, when its simply 100% untrue. CSS preloading and minimizing are solutions without a problem which some search engines (i.e. Google) have asked developers to implement, but which has shown very little effect on overall page rendering and paint performance, much less page rank compared to the download of these new gigantic JavaScript API's. Changing CSS design is like squeezing blood from a turnip. There is no evidence today changing CSS architecture or download strategies has any major effect on page rendering. These tech corporations are starting to now move away from that myth now. Besides, CSS has been downloading lightning fast in browsers for almost 25 years now with no extra help.

So, with 5G and fiber optic Internet why would there suddenly be a delay downloading 20 kilobytes of CSS?

The fact is, there is NO delay. It's almost zero. Minimization of CSS and HTML does nothing if your CSS is just a few dozen kilobytes, for example. A typical CSS file is very small compared to 1-5 Megabytes of JavaScript, images, video, or other resources downloaded to a typical web browser today. A lot of CSS is less than 100Kb, but the majority is probably less than 30Kb in a typical website today, even after minimization. If you use external script and styles in your site they will be cached for long periods of time in the user's browser. Revisits by your users to your site will reuse those same style sheets for days, weeks, or even months and keep your page rendering lightning fast when pulled from the browser cache compared to say using embedded styles which many JavaScript API's use that force reloads of the same CSS.

In addition, web browsers today are very smart at negotiating DNS calls and server connections, even though in the past browsers only had 2 connections by default (many use 6 connections by default today). That means external CSS and scripts often download in parallel and very quickly prior to HTML parsing and rendering begins. Because you never want unstyled HTML, this design works great and prevents the flash of unstyled HTML. Some kids today now hijack this natural browser process using tricks mentioned above which can create a huge mess where layouts shift, single-threaded scripts eat up CPU on phones to manipulate DOM's, HTML layouts rendered by scripts jump around, or half of web pages fail to load text content. Uncompressed images, on-demand video, large downloaded files, and huge JavaScript libraries create most major delays in web pages. So trust me...CSS is NOT the problem!

Huge Megabytes of blocking JavaScript is often the main culprit!

Many client-side, JavaScript API's today only get around their huge payload problem by trying to hijack the browser and preloading very tiny files on the homepage, but then behind the scenes make gigantic calls to volumes and volumes of script libraries, HTML pages, and resources with the assumption a user might visit other pages in the website. This can be a gamble and very wasteful and unnecessary if user's don't click where they expect. It loads a typical web browser with megabytes of cached but unnecessary scripts and resources, too. These scripting circus tricks are obviously a poorly thought out model, if you ask me.

Stay heavy server-side, not heavy client-side and your pages will be lightning fast!

For those reasons and more, as mentioned, I would avoid CSS and HTML "speed" tricks and focus on all the other bottlenecks.

Are separate css files always considered superior to inline styling? Even for one-off adjustments?

Yet, the internet tells me it is always preferred to keep all my style information in .css files. Who's correct?

You do realise you're asking the internet here...? ;)

Having had to redo several websites where styling had been applied using inline tags, I can say without any hesitation that I would never, ever use them myself. They are a nuisance to maintain and unless you're keeping a close record of where and what you have applied the inline styles, it is difficult to ensure that your changes to global css files will be respected throughout the site.

If you do need page-specific css classes and you don't want to put them in the global css file, add them to the page head in a <style> element. Putting all your css in a single file has the advantage that the users' browsers will load the file and cache it, so that it won't need to be reloaded on other pages of the site.

If you are finding you have a lot of tweaks to make all over the place, it suggests the design may need rethinking or refactoring. This is particularly the case with margins and padding--you can make a lot of work for yourself by choosing the wrong combination to apply spacing to your document elements.

What are the best practices for including CSS and JavaScript in a page?

Best practice would be to split each resources(scripts, CSS, images, etc.) into separate files. Which will allow browser to download and cache each resource for future reuse(even for other pages). But browsers have limit into six(on time of writing) parallel connections per one origin. That why a lot of external resources on page cause bad page loading performance and bad waterfall.

There are a lot of techniques to improve performance such as: bundling, domain sharding, image sprites etc. Also for some critical resources you can use inline technique. It allows browsers to use this resources instantly without additional requests. For example, you can embed all resources(image, CSS, scripts) that are required for loading indicator and browser will render it without additional requests.

For best development style do not embed resources and use separate files. In case you care about performance you should investigate waterfall of your page(e.g. here or network tab in developer tool of any browser) and use some techniques to improve it. If you are interested in this field I recommend you to read books below:

  • High Performance Web Sites by Steve Souders
  • Even Faster Web Sites by Steve Souders
  • High Performance Browser Networking by Ilya Grigorik

Note that this techniques are relevant only for HTTP 1.1. For HTTP 2.0 it will be only harmful because new version is designed to improve performance.

Why search engines use embedded style sheets rather than external style sheets in their homepage?

If I had to guess, they do this because, to them, that extra 100 milliseconds it would take for your browser to load the separate CSS file is important. Additionally, this guarantees that the HTML will never load without the CSS also loading, so there is no risk that the user will ever see an unstyled page.

I'd imagine there could also be some performance benefit when you're dealing with an obscene amount of traffic, where it might be preferrable to handle as few requests as possible, even if it means you use a bit more bandwidth (this is more speculation on my part however).

Those sites all use server side scripting, which means they can easily make the CSS rules be consistent across all pages. For example, they could have a CSS file that they automatically inject into every page before they send it to your web browser. On their end, they still would only have one CSS file to maintain, even though on your end, it looks like they have separate CSS on every page.

All this said, this doesn't mean you shouldn't have your CSS loaded from a separate file; what makes sense for a company serving billions of pages every day might not make sense for your project.

Is it possible to load external Style Sheet after Internal styles?

Yes.

Just put the <link> tag after the <style> tag, or make the selector in the external stylesheet more specific.



Related Topics



Leave a reply



Submit