Skip to content

Instantly share code, notes, and snippets.

@ttfkam
Forked from fearphage/async_defer_script.js
Last active May 19, 2016 18:34
Show Gist options
  • Save ttfkam/4321326 to your computer and use it in GitHub Desktop.
Save ttfkam/4321326 to your computer and use it in GitHub Desktop.
Added check for Opera, loading on DOMContentLoaded instead of load. Event only added if Opera has no native support. Replacing script child instead of insert/remove.
// ==UserScript==
// @name defer/async for Opera
// @namespace http://d.hatena.ne.jp/edvakf/
// @license Public Domain
// Updated by Miles Elam <miles@geekspeak.org>
// ==/UserScript==
(function(window, document, opera) {
function load_script(script, attr) {
return function() {
var script2 = script.cloneNode(true);
script2.removeAttribute(attr);
script.parentNode.replaceChild(script2, script);
};
}
if (!('async' in document.createElement('script'))) {
// support async and defer
opera && opera.addEventListener('BeforeExternalScript', function(e) {
var script = e.element;
if (script.hasAttribute('async')) {
setTimeout(load_script(script, 'async'), 10);
} else if (script.hasAttribute('defer') && document.readyState != 'complete') {
window.addEventListener('DOMContentLoaded', load_script(script, 'defer'), false);
} else {
return;
}
return e.preventDefault();
}, false);
}
})(this, this.document, this.opera);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment