Skip to content

Instantly share code, notes, and snippets.

@arkaitzgarro
Forked from samthor/safari-nomodule.js
Last active January 9, 2018 21:24
Show Gist options
  • Save arkaitzgarro/df5e5a0858d232d264d5dfd1de51af6e to your computer and use it in GitHub Desktop.
Save arkaitzgarro/df5e5a0858d232d264d5dfd1de51af6e to your computer and use it in GitHub Desktop.
Safari 10.1 `nomodule` support
/**
* Safari 10.1 supports modules, but does not support the `nomodule` attribute - it will
* load <script nomodule> anyway. This snippet solve this problem, but only for script
* tags that load external code, e.g.: <script nomodule src="nomodule.js"></script>
*
* Again: this will **not** prevent inline script, e.g.:
* <script nomodule>alert('no modules');</script>.
*
* This workaround is possible because Safari supports the non-standard 'beforeload' event.
* This allows us to trap the module and nomodule load.
*
* Note also that `nomodule` is supported in later versions of Safari - it's just 10.1 that
* omits this attribute.
*/
(function() {
var check = document.createElement('script');
if (!('noModule' in check) && 'onbeforeload' in check) {
var support = false;
document.addEventListener('beforeload', function(e) {
if (e.target === check) {
support = true;
} else if (!e.target.hasAttribute('nomodule') || !support) {
return;
}
e.preventDefault();
}, true);
check.type = 'module';
check.src = '.';
document.head.appendChild(check);
check.remove();
}
}());
/**
* Safari 10.1 modules support
*/
!function(){var e=document.createElement("script")
if(!("noModule"in e)&&"onbeforeload"in e){var t=!1
document.addEventListener("beforeload",function(n){if(n.target===e)t=!0
else if(!n.target.hasAttribute("nomodule")||!t)return
n.preventDefault()},!0),e.type="module",e.src=".",document.head.appendChild(e),e.remove()}}()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment