You probably want to include the rel="noopener"
or rel="noopener noreferrer"
attribute to prevent attacks.
That’s an improved snippet, please test it by yourself because I’m not a dev and just a random guy wearing sunglasses:
<script>
document.addEventListener("DOMContentLoaded", function() {
const links = document.querySelectorAll("a");
links.forEach(function(link) {
if (link.host !== window.location.host) {
link.setAttribute("target", "_blank");
link.setAttribute("rel", "noopener noreferrer");
}
});
});
</script>
It should be more secure, efficent and reliable than using jQuery, preventing third party surface/attacks.