Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery.clone() causes browser to hang

Why does the following jQuery code cause my browser to hang?

Caution: do not run this unless you are prepared to force quit your browser

<!DOCTYPE HTML> 
  <title>Simple clone</title> 
  <script type="text/javascript" src="jquery.js"></script> 

  <div>
    <script>$('div').clone().appendTo('body');</script>
  </div>

Edit

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.

Edit 2

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.

like image 647
RobG Avatar asked Jan 18 '23 03:01

RobG


1 Answers

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>
like image 64
Adam Rackis Avatar answered Jan 28 '23 22:01

Adam Rackis