Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mxdvl/bb4042dc1448745c3dc707dc771e0e1b to your computer and use it in GitHub Desktop.
Save mxdvl/bb4042dc1448745c3dc707dc771e0e1b to your computer and use it in GitHub Desktop.
Override document.createElement('script') to prevent 3rd parties injecting blocking scripts
<!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>
@SiAdcock
Copy link

I think this is the default behaviour of scripts added using document.createElement('script'). According to an 8 year old Jake Archibald article, anyway 😅

@mxdvl
Copy link
Author

mxdvl commented Sep 30, 2021

Ooh, excellent point! This seems to still be true according to javascript.info and MDN

@topbestcoder
Copy link

Mistake :
})(Document) ---> })(document)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment