Because my webpages are a bit heavy, I decided to use a preloader. The purpose of a preloader is to show some content before the main content loads, engaging the user from the start. Therefore it is very important to show preloader ASAP.
There is a slight problem though. Browser will typically wait for all CSS to be loaded before attempting to display and render HTML. This can be problematic if the document contains several biggish stylesheets.
So, my solution was thus:
<!-- In the head: -->
<noscript>
<link rel="stylesheet" href="/big-css1.css">
<link rel="stylesheet" href="/big-css2.css">
<link rel="stylesheet" href="/big-css3.css">
</noscript>
<script>
function LoadCSS(path) {
var head = document.getElementsByTagName('head')[0],
link = document.createElement('link');
link.setAttribute('href', path);
link.setAttribute('rel', 'stylesheet');
link.setAttribute('type', 'text/css');
head.appendChild(link);
}
</script>
<style>
/*preloader CSS is here*/
</style>
...
</head>
<body>
<div id="preloader">
Some nice content here
</div>
<!-- Main content starts below: -->
<div id="wrapper">
<script>
//hide main content until its loaded
//use JS and not CSS to support those with JS disabled
var el_preloader = document.getElementById("preloader");
var el_wrapper = document.getElementById("wrapper");
el_preloader.style.display = "block";
el_wrapper.style.display = "none";
LoadCSS('/big-css1.css');
LoadCSS('/big-css2.css');
LoadCSS('/big-css3.css');
</script>
...
<!-- After jQuery has been loaded -->
<script>
jQuery(window).load(function() {
document.getElementById("wrapper").style.display = "block";
jQuery('#preloader').fadeOut(1000, function () {
jQuery('#preloader').remove();
});
});
</script>
So, basically, if the use supports JavaScript, then JavaScript handles loading of stylesheets, and if JS is turned off, then the stuff inside the <noscript> tag is parsed and thus stylesheets are loaded normally.
This setup works fine in modern browsers, however I am not sure what impact it will have on SEO, considering Google and others are now evaluating user experience on the websites, and for that they need to parse CSS. Are they smart enough to render the website correctly with this solution? ARe there any adverse impacts on SEO with preloaders in general?
Thanks.
Related
In a (Wordpress) website's <head>, I have the following code to load an additional stylesheet after all dynamic html and inline CSS created by a (third-party) slider plugin has been created via JS:
<link rel="preload" as="style" type="text/css" href="<?php bloginfo('stylesheet_directory'); ?>/slider-styles1.css" onload="this.rel='stylesheet'">
The reason for the necessity to load that additional stylesheet later than the main stylesheet is that it contains some calc values for height settings which depend on other calculated (inline css) values created by the plugin which again depend on the the size of images loaded by the plugin. A rather complex thing, there was actually some trial and error involved before I got it working, since I don't know what the plugin actually does in which order.
My problem: This works in all current browsers, but in some older browsers (for example Firefox < 55, reported by a user with a very old computer) the related stylesheet is not loaded at all. Apparently (also according to caniuse) older browsers don't know <link rel="preload">.
So my question is if there is anything I can replace that line of code with, which also would work in older browsers?
It's not clear what the purpose is of this pattern:
<link
rel="preload"
as="style"
type="text/css"
href="<?php bloginfo('stylesheet_directory'); ?>/slider-styles1.css"
onload="this.rel='stylesheet'">
It is preloading a stylesheet, then after it preloads it's changing rel to stylesheet so that it loads for real. Usually rel="preload" is for kicking off a download of a resource that isn't loading up front ahead of schedule, prepping it in the cache, whether that's to avoid excessive download waterfalls or to let something that will be loaded dynamically later on will complete sooner.
Since in your case you're wanting it to always load the stylesheet on page load, there's no need to do anything with preloading. Just replace with this, and it should be compatible with browsers that don't support preloading:
<link
rel="stylesheet"
type="text/css"
href="<?php bloginfo('stylesheet_directory'); ?>/slider-styles1.css">
If the idea was to use this preload + onload as a way to delay loading stylesheet until after page load, a better approach may be to inject the link via some JavaScript:
<script>
var sliderStylesheet = "<?php bloginfo('stylesheet_directory'); ?>/slider-styles1.css";
document.addEventListener('load', function () {
var link = document.createElement('link');
link.setAttribute('rel', 'stylesheet');
link.setAttribute('type', 'text/css');
link.setAttribute('href', sliderStylesheet);
document.head.appendChild(link);
});
</script>
I found a solution myself: I added an ID to the <link> tag to be able to address it in a simple way and used a simple script wrapped inside a setTimeout function to change the value of the rel attribute.
Note: Since there is no visible content, there is no visible result in the following snippet window, but the code with the changed attribute can be seen when inspecting the snippet with the browser tools. It also works when the link is inside the <head> section, BTW, which is my real-world situation.
jQuery(document).ready(function() {
setTimeout(function() {
jQuery('#link_to_sliderstyles1').attr("rel", "stylesheet");
}, 200);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="preload" as="style" type="text/css" href="<?php bloginfo('stylesheet_directory'); ?>/slider-styles1.css" onload="this.rel='stylesheet'" id="link_to_sliderstyles1">
As a test to learn more about optimizing websites, I've been trying to get my site to have the perfect score on PageSpeed Insights. Everything is going great so far except for the CSS delivery.
I did manage to get a perfect result by using the preload tag, but for some reason that didn't load for Firefox. So I tried using other solutions.
I switched then over to this:
<link rel="stylesheet" href="~/css/site.min.css" media="none" onload="if(media !== 'all')media='all';">
<noscript><link rel="stylesheet" href="~/css/site.min.css"></noscript>
Which seemed very effective but pagespeed doesn't pick it up so it only gives me a 85 score rating.
Same happened when I used <link rel="stylesheet" href="~/css/site.min.css" media="none"/> in head and <link rel="stylesheet" href="~/css/site.min.css"> at the end of my body.
Then I tried loading my css with Javascript like this:
<noscript id="deferred-styles">
<link rel="stylesheet" href="~/css/site.min.css"/>
</noscript>
<script>
var loadDeferredStyles = function() {
var addStylesNode = document.getElementById("deferred-styles");
var replacement = document.createElement("div");
replacement.innerHTML = addStylesNode.textContent;
document.body.appendChild(replacement);
addStylesNode.parentElement.removeChild(addStylesNode);
};
var raf = requestAnimationFrame ||
mozRequestAnimationFrame ||
webkitRequestAnimationFrame ||
msRequestAnimationFrame;
if (raf) raf(function() { window.setTimeout(loadDeferredStyles, 0); });
else window.addEventListener('load', loadDeferredStyles);
</script>
But this also had the same effect! Pagespeed didn't pick it up and gave me a bad rating. Any reason why for this? Because the above code can be found on their site!
according to my experience with google pagespeed, for optimizing css delivery you have to write inline css code of first fold of your webpage.So that it can be painted fast, and rest of the css you can write in the external file. Minimize and concat css files used in the page. Refer this link for more info optimize css delivery
This is what I use just before the </body> and works fine.
<script type="text/javascript">
function downloadAtOnload() {
// Dynamically load CSS
var ls = document.createElement("link");
ls.rel="stylesheet";
ls.href= "css/my-css-file.css";
document.getElementsByTagName("head")[0].appendChild(ls);
}
if (window.addEventListener) window.addEventListener("load", downloadAtOnload, false);
else if (window.attachEvent) window.attachEvent("onload", downloadAtOnload);
else window.onload = downloadAtOnload;
</script>
I was running Google PageSpeed Insights on my website - www.gpsheatmap.com, and it suggested changing the loading of my stylesheets(https://developers.google.com/speed/docs/insights/OptimizeCSSDelivery#example) from -
<link href="/static/css/landing-page.css" rel="stylesheet">
To -
<script>
var cb = function() {
var l = document.createElement('link');
l.rel = 'stylesheet';
l.href = '/static/css/landing-page.css';
var h = document.getElementsByTagName('head')[0];
h.parentNode.insertBefore(l, h);
};
var raf = requestAnimationFrame || mozRequestAnimationFrame ||
webkitRequestAnimationFrame || msRequestAnimationFrame;
if (raf) raf(cb);
else window.addEventListener('load', cb);
</script>
I tried this for my stylesheets and it visibly changed the loading so you would see the pre-css view, then a second later you would see the stylesheet applied. This was in firefox
Should I disregard this approach, or can this be fixed?
You should consider the critical path and also put all the necessary style in your head section so as to avoid the FOUC (just the style for contents above the fold). This can be done either extracting the style by hand or — for larger sites — with an automatic task like critical-path-css-demo for gulp
Anyway if you choose to load all the stylesheets with javascript consider to still include them inside a <noscript> block, so they can be loaded also when JS is not available.
<noscript>
<link rel="stylesheet" ...>
</noscript>
As a further optimization for near-future browser (at this time it works only on Chrome Canary) it will be possible to early preload stylesheets using
<link rel="preload" href="..." as="style">
and to create an async loader in a simpler way
<link rel="preload" href="..." as="style" onload="this.rel='stylesheet'">
Another interesting and recent approach is described by Jake Archibald and it's called "Multi-stage CSS loading": it requires to load a small piece of CSS just before the markup that has to be styled and thus avoid the need for critical CSS, e.g.
<link rel="stylesheet" href="/site-header.css">
<header>…</header>
<link rel="stylesheet" href="/article.css">
<main>…</main>
<link rel="stylesheet" href="/comment.css">
<section class="comments">…</section>
The plan is for each to block rendering of subsequent content while the stylesheet loads, but allow the rendering of content before it. The stylesheets load in parallel, but they apply in series. This makes behave similar to <script src="…"></script>.
Back-story
I am creating a web application in which individual pages are "loaded" via the jQuery .load function. Originally the loaded page was a single file, but as it got longer I decided to split it into a .html file, a .css file, and a .js file.
Strangely, a single design flaw arose surrounding an element that was positioned using percentage values within the css. To see if I modified the styling while I moved, I replace the style tag (omitting the link tag instead) and it worked fine. Back and fourth a few times and I learned it was strictly occurring only when I used link tags rather than embedding it via style tags.
I wanted to use link tags, so I tried to narrow the problem down. After a while of fiddling, I traced it down to the .js file, specifically a usage of the .focus function on $(document).ready. If I comment out the .focus, everything works fine. Uncomment, and it breaks.
This appears to only happen in Chrome. It doesn't occur in FF26 or IE11.
Example
A fiddle.
Note that the problem only occurs in Chrome and that caching must be disabled. As Chrome's temporary cache disable doesn't extend into iframes of iframes, a direct result is easier to work with.
jQuery provides a callback function when the .load() method has completed and the DOM has been updated. This is where you would want to operate on elements that have been inserted from your external url.
<script>
$(document).ready(function() {
$('#content').load('html/portal.html', function() {
//now i can operate on elements loaded from html/portal.html
//they have been inserted into the DOM
$('input#input').focus();
})
});
</script>
As far as references to the link element, if you want to dynamically load a stylesheet from an external url using javascript you can employ a javascript function something like this:
//load deferred stylesheets
function loadStyleSheet(src) {
if (document.createStyleSheet) {
document.createStyleSheet(src);
} else {
$("head").append($("<link rel='stylesheet' href='"+src+"' type='text/css' media='screen' />"));
}
}
If you want to load an external javascript file you can use jQuery.getScript():
jQuery.getScript('/js/external.js');
So putting all of this together, if you want to load some content from an external resource, insert it into the DOM and the load an external stylesheet and an external javascript resource you could do so as follows:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
$(document).ready(function() {
//function to load a deferred stylesheets
var loadStyleSheet = function(src) {
if (document.createStyleSheet) {
document.createStyleSheet(src);
} else {
$("head").append($("<link rel='stylesheet' href='"+src+"' type='text/css' media='screen' />"));
}
}
$('#someWrapper').load('external-url.html #someWrapper > *', function() {
loadStyleSheet('/css/external.css');
jQuery.getScript('/js/external.js');
})
});
</script>
</head>
<body>
<div id="someWrapper">
<!-- external content is loaded here -->
</div>
</body>
</html>
I used to build my websites based on the HTML5 Boilerplate: styles and modenizr in the head, jQuery (google CDN or hosted file) and scripts before the closing body tag. Something like that:
<!DOCTYPE html>
<!-- modernizr conditional comments here -->
<html class="no-js">
<head>
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/main.css">
<script src="js/vendor/modernizr-2.6.2.min.js"></script>
</head>
<body>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.10.2.min.js"><\/script>')</script>
<script src="js/plugins.js"></script>
<script src="js/main.js"></script>
</body>
</html>
Now I want to remove all render-blocking below-the-fold css and js as suggested by Googles PageSpeed Insight.
How do I defer the css and js files including the jQuery library loaded from google?
What should I do about modernizr?
To remove this particular warning you need to do the following:
defer the load of all external CSS until after page onload
defer the load of all external JS until after page onload
In practice that means you need to do the following:
split your CSS into that required to avoid the "flash of unstyled content" (FOUC) and the rest
split your javascript likewise
inline the CSS and JS that is required
defer the load of the other CSS and JS until after page onload.
Using build tools is the only sane way of doing this. You can do it with various Grunt tools, or with the ant-based H5BP Build Script.
The basic method of deferring loads is as follows:
(function () {
// Load jQuery after page onload
function loadJS() {
var url = "https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js";
var n = document.createElement("script");
n.src = url;
n.onload = loadJS1;
document.body.appendChild(n);
}
// Load some JS after jquery has been loaded.
function loadJS1() {
var url = "js/main.js";
var n = document.createElement("script");
n.src = url;
// Continue chaining loads if needed.
//n.onload = loadJS2;
document.body.appendChild(n);
}
// Check for browser support of event handling capability
if (window.addEventListener) {
window.addEventListener("load", loadJS, false);
} else if (window.attachEvent) {
window.attachEvent("onload", loadJS);
} else {
window.onload = loadJS;
}
})();