Why does the following jQuery code cause my browser to hang?
<!DOCTYPE HTML>
<title>Simple clone</title>
<script type="text/javascript" src="jquery.js"></script>
<div>
<script>$('div').clone().appendTo('body');</script>
</div>
For those in the "infinite loop" camp, that should not be an issue. A perfectly safe (non-jQuery) version is:
<div>div
<script>
var el = document.getElementsByTagName('div')[0];
document.body.appendChild(el.cloneNode(true));
</script>
</div>
So the issue is specifically related to how jQuery does clones.
It seems that jQuery causes script elements in clones to be executed. That isn't standard behaviour and is something about how jQuery does clones that is quite unexpected.
Because you're cloning a div that has inside of it a script that says to clone all divs. The original div's script that says to clone all divs is cloned too, and so on, ad infinitum
Of course you could do:
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(function() {
$('div').clone().appendTo('body');
});
</script>
<div>
Safe Now
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With