JQuery.clone () makes the browser hang

Why is the following jQuery code freezing my browser?

Caution: do not run this if you are not ready to force exit the 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 who are in the “endless cycle” camp, this should not be a problem. Perfectly safe version (non-jQuery):

  <div>div <script> var el = document.getElementsByTagName('div')[0]; document.body.appendChild(el.cloneNode(true)); </script> </div> 

So the problem is how jQuery does cloning.

Edit 2

JQuery seems to call script elements in clones. This is not standard behavior and something about how jQuery makes clones, which is completely unexpected.

+4
source share
2 answers

Because you are cloning a div that has a script inside that says to clone the entire div. The original div script that says to clone all divs is also cloned 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> 
+7
source

This is an endless cycle. You clone a div that contains a script that clones 2 divs that have a script that clones 4 ...

+2
source

Source: https://habr.com/ru/post/1384627/


All Articles