开发者

Why doesn't jQuery's $.get() insert script elements into the DOM?

开发者 https://www.devze.com 2023-01-15 09:42 出处:网络
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 elemen

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 ge开发者_运维知识库t 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:

Note: script elements inserted using innerHTML do not execute when they are inserted.

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.


Script elements are not binded to document when you do this. You need to insert the script yourself.

One way to do that is by calling a callback function that parsers your return html and insert the script manually. Like this one: `

_insertScripts: function(html) {
        var sfrag = '<script[^>]*>([\\S\\s]*?)<\/script>';
        var matchAll = new RegExp(sfrag, 'img');
        var matchOne = new RegExp(sfrag, 'im');
        if(html.match(matchAll)) {
            $.map(html.match(matchAll), function(script) {
                eval( (script.match(matchOne) || ['', ''])[1] );
            });
        }
    }

`

I've seen some solutions that use the live() function from jQuery also, but I'm not sure on how it works.

0

精彩评论

暂无评论...
验证码 换一张
取 消