Skip to content

Instantly share code, notes, and snippets.

@colingourlay
Last active August 29, 2015 14:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save colingourlay/400ba0286417ac02254d to your computer and use it in GitHub Desktop.
Save colingourlay/400ba0286417ac02254d to your computer and use it in GitHub Desktop.
Soft page load script
// This script applies an is-loading class to the html element,
// which is then replaced by an is-loaded class after a timeout
// of 2 seconds. This can be triggered prematurely by calling
// window.KILL_LOADING_STATUS (while it exists).
// Combined with the injected style, this sets the opacity of
// the body content to 0, then fades it back to 1.
// This is useful for pages that heavily modify the page after
// rendering, and you want to hide the reflows from visitors.
(function (htmlEl) {
var stylesheet = '<style>' +
'html.is-loading > body { opacity: 0; }' +
'html.is-loaded > body { opacity: 1; transition: opacity 1s; }' +
'</style>';
var timeoutDuration = 2000;
var timeout;
function done() {
html.className = html.className.replace(' is-loading', ' is-loaded');
window.KILL_LOADING_STATUS = null;
}
function kill() {
clearTimeout(timeout);
done();
}
if (htmlEl) {
document.write(stylesheet);
htmlEl.className = htmlEl.className + ' is-loading';
timeout = setTimeout(done, timeoutDuration);
window.KILL_LOADING_STATUS = kill;
}
})(document.documentElement);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment