Script Execution - innerHTML, jQuery html ()
Without getting into theoretical questions about why jQuery chose to do this, jQuery html()
behaves differently than native innerHTML
. By default jQuery will find script tags in HTML and load asynchronously. If this behavior is undesirable, you can use $.parseHTML
to prevent this from happening by setting the third argument to false
.
$("body").empty().append($.parseHTML("<script>alert(11);</script>", document, false));
Please note that script tags will not be added to the DOM using this method.
Conversely, if you want to achieve the same effect as your jQuery statement in vanilla JS, you can do the following.
var script = document.createElement('script');
script.text = 'alert(11);';
document.body.innerHTML = '';
document.body.appendChild(script);
source to share
Using innerHTML will stop the script execution according to the documentation in simple terms, without going into details.
<script type="text/javascript">
var script = document.createElement('script');
script.appendChild(document.createTextNode("alert('11')"));
document.body.appendChild(script);
</script>
source to share