I am using $.get() to retrieve an HTML snippet from a remote server and insert that snippet into the DOM. The snippet contains several basic HTML elements and a script element. All of the basic elements get inserted, but the script element does not.
Example snippet:
<p>This is a paragraph</p>
<script type="text/javascript">
// JavaScript that will work with the HTML in the snippet
</script>
I have verified that the script element is in the retrieved snippet by looking at the resources retrieved in Chrome’s web inspector. So, why doesn’t $.get() insert the script element and is it possible to do what I am wanting to do?
Edit:
To clarify, I was retrieving the HTML snippet with $.get() and inserting it into the DOM with $().html(data).
The script element should be inserted, just as static content – the script will not execute. When you use html() to insert html, it maps to each element’s innerHTML property. Historically, browsers don’t execute script elements inserted this way (with the exception of IE in certain circumstances).
This is also reflected in the definition of innerHTML in the draft HTML 5 specification:
If you want to execute the script, you could look up the element and eval() its text, or create a new script element from the text and insert it into the DOM properly.