Last active
August 29, 2015 14:19
-
-
Save colingourlay/400ba0286417ac02254d to your computer and use it in GitHub Desktop.
Soft page load script
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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