1

According to Can scripts be inserted with innerHTML? I can use jquery getScript() Method to execute a remote javascript file loaded with Ajax.

But in my case, my script file is within an html file.

So does jquery have a method which can also cope with mixed html and javascript, or should I have to parse the file to separate all javascript from html and then inject them dynamically ?

If I just read all the file and put it in innerHTML, as javascript doesn't work, does it mean innerHTML is already cleaned from any javascript and I just need to inject the script within ?

What I'd like is to have the equivalent DOM of if I could include the html statically with an import.

Community
  • 1
  • 1
user310291
  • 36,946
  • 82
  • 271
  • 487
  • If I understand right, you have a html file which have some JS code in its script tag, and you want to import this file and only load JS code. right? – Rajesh Dec 24 '15 at 17:19
  • @Rajesh yes like html 5 import http://www.html5rocks.com/en/tutorials/webcomponents/imports/?redirect_from_locale=fr except it isn't yet a standard and even if it was, I need to have this work for IE 8 so using Ajax – user310291 Dec 24 '15 at 17:22
  • Ideal way would have been if you could move this code in a sperate js file, but for now you can try a workaround. Read html file as string using ajax and then strip script tag and using createElement("script") create script and append to head. Not sure if it's the best way. – Rajesh Dec 24 '15 at 17:29
  • I closed your earlier question as a duplicate of http://stackoverflow.com/questions/1197575/can-scripts-be-inserted-with-innerhtml. The answers to that question explain how to do it, including the answer I gave below. – Barmar Dec 24 '15 at 17:29

1 Answers1

1

jQuery will execute the HTML if you insert it into the DOM with .html(). You can also use .load(), which is just shorthand for $.get that calls .html() in its callback.

So you can do:

$("#somdiv").load("filename.html");

It will load the HTML into the DIV, and execute any <script> blocks that were in the HTML.

Barmar
  • 741,623
  • 53
  • 500
  • 612