I am currently trying to implement smoothState.js on my website. I have, however, run into a problem when transitioning between pages.
The problem is that the new content is 'unstyled' (more accurately put it is styled with the styles of the previous page). Since I have focused quite a lot on performance for this site, I would prefer if there was a way in which I could avoid combining the stylesheets.
I have thought a bit about how to tackle this problem, but cannot decide which of the solutions would have least performance impact. These are the possible solutions which I could think of.
1. Combine the stylesheets
Despite me being reluctant to do this, it might be the best way. After all, it is only a few extra bytes, right? Stylesheets (minified and gzipped) are quite small, after all.
2. Add a javascript function to the body
For smoothState, I am currently using the body as the container. I guess that I could thus, for example, add the following javascript directly after the body tag.
var cb = function() {
var l = document.createElement('link'); l.rel = 'stylesheet';
l.href = 'css/single.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);
(I would have to modify the above since document.load isn't run when changing pages with smoothState. Sadly, I am quite terrible at vanilla JS. But I guess I can figure it out... Not a big problem :) )
3. Do some javascript magic in the onStart.render() of smoothstate() Thirdly, and lastly, I realise that it would be plausible to run some javascript to get the stylesheet of the target page and append it to the new. My instinct tells me this will be less efficient performance wise than just combining the stylesheets...
In case it helps, I will include my smoothState function below.
'use strict';
var $body = $('html, body'),
content = $('#main').smoothState({
prefetch: true,
pageCacheSize: 4,
development: true,
onStart: {
duration: 250,
render: function (url, $container) {
// #3 would be implemented here.
content.toggleAnimationClass('is-exiting');
$body.animate({
scrollTop: 0
});
}
},
onProgress : {
duration: 0,
render: function (url, $container) {
$body.css('cursor', 'wait');
$body.find('a').css('cursor', 'wait');
}
},
onEnd: {
duration: 250, // Duration of our animation
render: function (url, $container, $content) {
$body.css('cursor', 'auto');
$body.find('a').css('cursor', 'auto');
$container.html($content);
}
}
}).data('smoothState');
})(jQuery);
Can anyone suggest which of the three methods provided would have the least impact on the page-load of my pages, or suggest another method of tackling the problem?
UPDATE 28/04/15 I have chosen to simply go with method number 1 and combined the stylesheets.