How to use both rel="preload" and rel="stylesheet" for the same tag? - css

Google Pagespeed test doesn't recognize preload when it is used together with stylesheet. I tried
<link rel="preload stylesheet" href="http://www.example.com/style.css" />
and it still shows "Consider using to prioritize fetching resources that are currently requested later in page load.". If I remove stylesheet from rel attribute, it recognizes the preload.
I was thinking to try this:
<link rel="preload" rel="stylesheet" href="http://www.example.com/style.css" />
but I am not sure if you can have 2 the same attributes for the same link tag. Would this work?

For loading CSS styles asynchronously, you should indicate it, as a preload stylesheet. Whenever you use rel="preload" alone, it won't transform to stylesheet on page load and it will remain as preload, so to indicate it as stylesheet you should use another attribute such as as which indicate the type of element and in your case, it should be style. Then you need to tell the browser whenever the loading process got finished you need to consider this as a stylesheet, so you have to define another attribute like onload and then define its real relation.
so you have to import it like this:
<link rel="preload" as="style" onload="this.rel='stylesheet'" href="http://www.example.com/style.css">
NOTE: You can read more about it here in google developers.
UPDATE
Since preload is not supported in firefox until now (according to this), the only way to do it, is to declare it twice in the one rel tag or two separate tags.
<link rel="preload" as="style" href="http://www.example.com/style.css">
<link rel="stylesheet" href="http://www.example.com/style.css">
Or
<link rel="stylesheet" rel="preload" as="style" href="http://www.example.com/style.css">
NOTE: As #JohnyFree tested the second one (one with a line through) in the Google page speed, it won't be recognized as valid preload style, whilst the format is valid according to W3.org.

preload https://web.dev/defer-non-critical-css/
<link rel="preload" as="style" onload="this.onload=null;this.rel='stylesheet'" href="http://www.example.com/style.css"/>
fallback for not supported browsers https://www.filamentgroup.com/lab/load-css-simpler
<link rel="stylesheet" media="print" onload="this.media='all'" href="http://www.example.com/style.css"/>

If you feel you need to do this Javascript circus trick to save a few hundred milliseconds, I recommend the version below. Use it instead if you want cross-browser support:
<link media="print" onload="this.media='all'" rel="stylesheet" type="text/css" href="style.css" />
Why does this work? In nearly all browsers going back to the 1990's, support of linked "print" media type style sheet was universally supported. Linked print style sheets were only used when printing pages. Because browsers knew the "sheet" media type must always be downloaded before "print", they often delayed or downloaded sheets with "media=print" asynchronously. Nothing was needed by the page author. It has worked this way for many years in most browsers, naturally.
Recently, developers trying to follow Google's new ranking policies discovered this trick to stop some styles from blocking others or from downloading immediately. They then realized the "print" media type was the only built-in, cross-browser way to fool browsers into delaying downloading of style sheets.
Turning your style sheet into a "print" type using the trick above doesn't mean its "print", as the script later changes it back to "all". It is simply a "hack" or way to prevent modern browsers from downloading your CSS styles in parallel with other sheets.
Note: "all" is not supported in a wide range of older browsers including Internet Explorer versions 1-7, so a bad idea, anyway.
Stopping one or two style sheets from blocking another sheet from downloading would be the only reason to use this trick, and assumes you are using a HUGE style sheet that is 50+ kilobytes in size and use a server with slow connections.
RECOMMENDATIONS?
I recommend you do NOT ever "preload" CSS for the following reasons!
Just because Google flags this as an issue in Lightspeed, doesn't mean filling your webpages up with duplicate style links and elaborate JavaScript hacks to shave off a 100 milliseconds is a good idea. You should care more about the quality and integrity of your HTML pages above all other concerns, including speed or advertising-driven search engine demands!
There could be racing issues! What happens when your HTML downloads before your async "print" sheet resolves itself back to "all"? You may see a flash in some browsers where the HTML downloads first and rendering begins before the async styles are downloaded. Your user then sees your website layouts and fonts move or shift. Nasty!!
Async'ing CSS is kinda pointless compared to these poorly designed Javascript frameworks kids are downloading in 2021 that waste download times anyway. Most style sheets are 50 kilobytes or less in size compared to the MASSIVE 500-1500+ kilobytes most modern Javascript frameworks shove into the browser today (ie. React, Angular, Ember, etc.). These downloads often "embedd" the same CSS over and over into the browser's cache anyway, forcing a reload of the same CSS each site visit unlike CSS linked styles which can be cached for months! So preloading linked CSS makes no sense if its reloaded every visit. So what is the point?
Many browsers may crash and burn with this trick! The preload is not widely adopted anyway, so you run a huge risk in a percentage of your users
seeing an unstyled web site if you use this "hack". Imagine 5%-10% of your users seeing your website displayed in the default 'Times Roman' font and a white block-level, unstyled content page because you wanted to save 500 milliseconds of download time? Sorry, not worth the risk!
Most old browsers had only 2 open connections allowed when downloading files, so they were limited by open connections, not style sheet downloads. Many modern browsers have 6 maximum. So again, connections are the bottleneck here when combined with multiple open JavaScript calls, not style sheet downloads. So little is gained using this trick.
Slow Servers are Often the REAL Bottleneck: Server delays on opening connections on the server can be huge bottlenecks. Even if your host provider or web application like Wordpress is using cached images, pages, and proxies but your waiting hundreds of milliseconds for a connection to open up on the server, all that becomes meaningless. CDN's can also fail, be delayed, blocked, etc., too.
The number one factor delaying downloads, besides slow servers and giant JavaScript API libraries, is more often huge image files. Consider using new HTML5 'picture' elements with multiple image types like "WebP" that are highly compressed. If you page has "on-demand", non-streaming video, that also must be set to preload or download asynchronously. Adding "width" and height" values to force 'alt' attribute placeholders, as images download will create reserved dimensions in your page layouts so they don't shift waiting images to download. You will be amazed at the savings in download times and bottlenecks prevented when you focus on image and media issues, not CSS.
All that makes preloading CSS pretty worthless as far as website improvements. I would go look at the multiple Bootstrap, JavaScript modules, and JQuery file downloads stacked up in your browser grabbing limited, shared browser connections and focus on less scripts. 30 or so kilobytes of CSS will likely not be the issue.

Firefox has supposedly enabled "preload" in version 85, but it doesn't seem to work correctly. What I found that this code below works:
<link rel="preload stylesheet" as="style" href="style.css">

Related

Newspaper Wordpress theme page insights preload problem

This is my first qeuestion here.
I have searched for a solution to this, but whatever I've tried did not work.
I use Newspaper theme on my website and one of the problems which causes around 6 seconds of delay of mobile website loading is the problem with the newspaper.woff fond preloading.
I have added the following code to functions.php for both mobile and desktop version:
// Preload Newspaper fonts for responsive theme (main theme)
function dns_prefetch_responsive() {
echo "<link href='https://jakaoferta.pl/wp-content/themes/Newspaper/images/icons/newspaper.woff?19' rel='preload' as='font' type='font/woff' crossorigin>";
}
add_action( 'wp_head', 'dns_prefetch_responsive', 0 );
Also, added this to header.php:
<link rel="preload" href="/wp-content/themes/Newspaper/images/icons/newspaper.woff?19" as="font" crossorigin>
However, Google PageSpeed does not understand this has been done and still shows the issue.
On GtMetrix it is shown I load the font from two sources now.
What should I do so that this will start working properly?
when trying to preload font crossorigin should be set to anonymous (eg: crossorigin="anonymous") fonts are expected to be fetched anonymously, without this attribute, the preloaded font is ignored by the browser, and a new fetch takes place.
You should also use direct pathing instead of url pathing. This is ok /wp-content/themes/Newspaper/images/icons/newspaper.woff?19 ... This is not ok https://jakaoferta.pl/wp-content/themes/Newspaper/images/icons/newspaper.woff?19
<link rel="preload" as="font" type="font/woff" href="/wp-content/themes/Newspaper/images/icons/newspaper.woff" crossorigin="anonymous">
You can instead use the rel="prefetch" attribute to tell the browser to prepare the download of the resources that may be required later during page load or user actions so it will assign a low priority to those resources. This will result in a default load font then a switch to the custom one later on. (we're not waiting on the font to load before showing the content, which is I think default behaviour).
Stuff to know regarding font loading and browser default behaviours... Edge (even tho nobody use it) uses a system font until the custom font is ready, then swaps out fonts.
Chrome will hide text for up to 3 seconds. If text is still not ready, it will use a system font until the custom font is ready. Firefox will hide text for up to 3 seconds. If text is still not ready, it will use a system font until the custom font is ready. Safari hides text until the custom font is ready.
Taking a look at your website page-source I can see that you're currently loading your font 3 times (probably once in style.css, once in function.php and once in header.php), which is probably causing major performances loss. loading it only once is sufficient. Loading through cc is the least recommended regarding performances. Best practice is to register and enqueue from function.php
Following is the output from your website source code:
<link href='https://jakaoferta.pl/core/assets/13c402efbe/images/icons/newspaper.woff?19' rel='preload' as='font' type='font/woff' crossorigin='anonymous'>
<link rel="preload" as="font" href="https://jakaoferta.pl/core/assets/13c402efbe/images/icons/newspaper.woff?19" data-wpacu-preload-font="1" crossorigin>
<link rel="preload" as="font" href="https://jakaoferta.pl/core/assets/13c402efbe/images/icons/newspaper.woff?19" data-wpacu-preload-font="1" crossorigin>
Finally i would highly suggest using Google Fonts https://fonts.google.com/ for future projects. Google Fonts makes product and web pages run faster by safely caching fonts without compromising users’ privacy or security. Cross-site caching is designed so that you only need to load a font once, with any website, and we'll use that same cached font on any other website that uses Google Fonts.
In short, if somebody visit a website that uses the same Goole font, upon visiting your website that person wont have to download it nor cache it again.

Render blocking and CSS

I imagine this has been asked time and time again, but i've not seen the answer I'm looking for.
Im doing some simple tests with a HTML file and CSS file trying to stop the page from render blocking the CSS, running the site through page insights ( google )
Now i've seen answers like this:
<link rel="stylesheet" href="style.20180530.css?ver=1.0" media="none" onload="if(media!='all')media='all'">
and I've seen answers like this:
<link href="https://fonts.googleapis.com/css?family=Roboto:300,700" rel="preload" onload="this.rel='stylesheet';this.removeAttribute('onload');" as="style">
Both of which I am fine with, for the google fonts! But not for the main styles of the page, I don't think its a good user experience to see a page with no styles and then all of a sudden they load in.
Obviously you can eliminate any blocking of CSS by sticking the whole lot as inline styles, but again I don't think this is good practice, you're outputting all styles to a HTML page and not loading them via a style sheet.
I've seen sites actually load the styles like so:
<link rel='stylesheet' id='main-css' href='./style.2018052108.css?ver=4.9' type='text/css' media='all' />
Heres a link to the page insight speed test on the. I know the site is running wordpress. If you view page source it uses the exact same as i've used above.
And they aren't Render Blocking at all... How?
Im on a https I'm using cloudflare and my style sheet is compressed and only around 24bytes and I'm still getting render blocking.
Why?
How to avoid it?
The CSS loaded as an external request is always render blocking, you can't avoid it. The recommendation on pagespeed insights is that you don't do any css request before the content is loaded, in order to avoid the unstyled effect they suggest that you inline the CSS needed to display the content before the fold.
The page on your example is doing exactly that, they inline some css content (check the source code and search for the style tag), then, when the content is loaded they add an external stylesheet with javascript.
All that said, this is a recommendation, you can ignore it if you are happy with the performance of your page, if you want to follow the recommendation you can apply some techniques to achieve this in an automation way.
As always, in css-tricks you have a great introduction post to these techniques: https://css-tricks.com/authoring-critical-fold-css/
The key to the Google PageSpeed insights is above-the-fold render blocking. If you check the site that you linked as your page speed test reference, there are no strictly inline styles - you are correct. However, they have a <style>...</style> block inside of their <head> that sets all of their most important styles for above-the-fold content. That means those styles render immediately, and all other supporting styles will load soon after - but your visitors (and Google PageSpeed) will not notice the difference.

Shopify: Can't load external stylesheet from another server

https://friends-with-you.myshopify.com/
I'm trying to develop my first shopify theme. I'm trying to load a stylesheet which is hosted on another server, but the CSS is not loading. If I copy and paste that CSS directly into a file in the shopify theme, it works.
<link type="text/css" rel="stylesheet" href="http://fwy.pagodabox.com/magic/themes/fwy/fwy.css" />
What am I doing wrong at the above URL, and why isn't the css loading?
thanks!
Can you load your CSS file over both http and https? If so, change your tag to look like this:
<link type="text/css" rel="stylesheet" href="//fwy.pagodabox.com/magic/themes/fwy/fwy.css" />
That way whether a user visits using http://yourstore.com or https://yourstore.com, they'll get the stylesheet served using the protocol they're on (and you won't get any mixed content warnings).
A little more background: http://paulirish.com/2010/the-protocol-relative-url/
Under IE7 and IE8, using this in a <link> tag will result in your content being fetched twice.
Change your link tag to use a secure URL:
<link type="text/css" rel="stylesheet" href="https://fwy.pagodabox.com/magic/themes/fwy/fwy.css" />
^
The URL you're using now works fine on its own, but since you're browsing to the Shopify store over SSL, many web browsers are going to be hesitant to load the CSS over an unsecured connection.
I just checked and pagodabox serves the CSS file just fine over SSL.
In normal HTML documents one can load stylesheets from anywhere, as long as they exist and you're able to load them by typing the URL in (which I can).
I see the page as two navigation bars with a logo on the left hand side. There are hover states with transitions to a colour background on each item. Although, when I loaded the page, Chrome warned me not to load supposedly insecure content. Before this is loaded I just see text in Times New Roman. I think this is you problem.
I use themes with WordPress and style-sheets come with them (mostly). I don't see why you couldn't just put the style-sheet in with the rest of the theme.
Overall, the answer is yes (normally) but in this case browsers may regard it as un-safe and therefore not load it.
Yes you can! But it is faster to host the stylesheet on your server/where the other files reside. If you plan to include a stylesheet from elsewhere, you could run into problems of that server being down/busy and hence your theme will not display as required. As #Blieque mentioned, some browsers may question external content causing unnecessary warning popups to a user/user-agent.

How to Prevent Browsers from Caching CSS Files?

When I make a page, link it to a CSS file, and open it in a browser, it works fine.
But if a make a change and refresh the page again between very short time periods, the change is not reflected. But after sometime, when i refresh the page again, the changes appear.
So, somehow the browser keeps the CSS file cached and expires it after sometime. How to make the browser cache no CSS or HTML file.
It would be better if i can block it on a particular domain.
I'm on Ubuntu, using Chrome and Firefox, trying to prevent browsers from caching CSS files on 'localhost'... How to do it...
Thanks...
Something as simple as this should work:
<link rel="stylesheet" src="/css/screen.css?v={CURRENT_TIMESTAMP}">
Just replace {CURRENT_TIMESTAMP} with the actual timestamp in your server side code. This makes the browser think it's a new file because of the query string and it will be downloaded again. You could also use the actual modification time of the file (filemtime('/path/to/css/screen.css') if you're using PHP) which should prevent unnecessary downloads.
You can open Developer Tools by pressing Ctrl+Shift+J and then you'll find a cog icon in bottom right. When you click on it you should see an option to disable caching.
It would help to know how the website is hosted, as you can configure this in most web servers.
Also, it's a good idea to introduce a cache busting mechanism which would modify the links to the CSS files in question when you change the CSS files' contents. Browsers would then reload the CSS file because the HTML refers to a different URL.
A good example of a cache busting mechanism is the ruby on rails 3.1 asset pipeline which also minifies files and gzips them if the browser supports them:
Rails 3 - Asset Pipeline -- What does it mean to me?
http://2beards.net/2011/11/the-rails-3-asset-pipeline-in-about-5-minutes/
The seemingly-inelegant but rock solid approach is to give the asset a new name, when the content changes. This solves the problem for all your users, not just you:
<link rel="stylesheet" src="/css/screen_034.css">
<link rel="stylesheet" src="/css/screen_035.css">
<link rel="stylesheet" src="/css/screen_036.css">
Or maybe (but it's more of a pain to change in an IDE, and sometimes causes unrelated problems with caching):
<link rel="stylesheet" src="/css/screen.css?pretend_version_number=034">
Nothing else works quite as well in large scale production environments, where millions of copies of an older css file may be sitting in various intermediate or browser caches. Some clients ignore cache control headers, and you don't really want caching subverted anyway, at least not in production.
In development you can press Ctrl+Shift+J (Chrome) and turn off caching.

css file not getting updated

the font of the content of my facebook app keeps getting italicized even when i've removed the italics from the css file. if i make minor changes in the css file and upload it to the server, the firebug shows the unedited previous css file and hence, the app keeps showing unformatted content. what exactly is going wrong here?
i made a new css file and copied the contents of the previous css exactly as it was, and i linked it in all the files which require css. but when i upload these files to the server, facebook canvas doesn't show any css at all. i replaced the css filename with the previous one, and it works. why is this?
Actually it looks like facebook is currently experiencing some weird problems with styling. It doesn't cache any new styles, only displays what was previously cached (from yesterday). If you provide a new stylesheet url it will not be able to pull it up (like that url doesn't exist).
During normal conditions what others already suggested should work.
Facebook does like to cache things. Persistently. I don't know why the new file wouldn't have worked, by I can recommend 'spoofing' your css filename with a spurious querystring variable, and incrementing it each time you make an update.
eg
href="my_css_file.css?x=1"
Sounds like the browser is caching your CSS file, which is why even Firebug sees the older version.
There are numerous ways you can prevent the browser from caching your CSS file during development (once in production mode, you probably want it to remain in the cache). The most common technique used by web frameworks like Ruby on Rails is to append a random query string to the URL, like so:
<link rel="stylesheet" type="text/css" href="style.css?96234987" />
...but the trick is that it should be different every time, so the browser thinks it's a different file.
Here are links to a simple trick for PHP, a JSP example, and other possible methods.
According to Include files on facebook developer wiki:
Stylesheet includes are cached automatically by Facebook. Just include a tag like:
<link rel="stylesheet" type="text/css" media="screen"
href="http://yourapp.com/stylesheets/style.css?v=1.0" />
Increment the version number upon each change to your style sheet, as specified above.

Resources