Forked from sndrs/non-blocking-document.write.html
Last active
January 22, 2024 23:16
-
-
Save mxdvl/bb4042dc1448745c3dc707dc771e0e1b to your computer and use it in GitHub Desktop.
Override document.createElement('script') to prevent 3rd parties injecting blocking scripts
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
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>Prevent non-async script</title> | |
<script> | |
(function(Document) { | |
const trueCreate = document.createElement.bind(document); | |
Document.prototype.createElement = function(tag, options) { | |
const script = trueCreate(tag, options); | |
if(tag === 'script') script.setAttribute('async', ''); | |
return script; | |
} | |
})(Document) | |
</script> | |
</head> | |
<body> | |
<div>div 1</div> | |
<script> | |
const s = document.createElement("script"); | |
s.setAttribute("src","https://code.jquery.com/jquery-3.6.0.min.js"); // for the lolz | |
document.getElementsByTagName("head")[0].appendChild(s); | |
</script> | |
<div>div2</div> | |
</body> | |
</html> |
Mistake :
})(Document) ---> })(document)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Ooh, excellent point! This seems to still be true according to javascript.info and MDN