0

I am having some performance issues using .html() method of jQuery because it was being really slow. So I searched for alternatives and I found some:

So I am now replacing the .html() by the method suggested. But now I have another problem:

Javascript that is inside the Html to be added is not being executed.

I have written a simple fiddle to show what is happening:

Can anyone suggest how could I solve this because I need the javascript to be executed.

Community
  • 1
  • 1
amp
  • 11,754
  • 18
  • 77
  • 133
  • Check this out ... http://stackoverflow.com/questions/2592092/executing-script-elements-inserted-with-innerhtml – bayblade567 Mar 28 '15 at 21:30
  • Yes, in the by babyblade567 mentioned question have a look at the answer with stripandexcute function. This is working for me. See this [jsFiddle](https://jsfiddle.net/awolf2904/bbsLy56d/3/). I only had to change `innerText` to `innerHTML` in the script. – AWolf Mar 28 '15 at 21:40

2 Answers2

1

You might need to eval() the script:

var container = document.getElementById("container"),
    content = document.getElementById("content");

$("#button2").on("click", function(){
    container.innerHTML = content.innerHTML;
    var scripts = container.getElementsByTagName('script');
    for(var i=0, l=scripts.length; i<l; i++) eval(scripts[i].innerText);
});

JS Fiddle Demo

blex
  • 24,941
  • 5
  • 39
  • 72
0

For me the first button fires the script, the second doesn't.

That is because .innerHTML only refers to text within an element, not scipts or other tags.

dargmuesli
  • 612
  • 10
  • 20