开发者

Jquery load with script tags

I read something about the .load function in jQuery. Is there a way to insert t开发者_JAVA技巧he script tags in the loaded page?

When I try to load a page the scripts doesn't load :s, I want to fix this. And getscript() isn't a option.


When .load() returns HTML content that contains <script> tags, jQuery strips out the <script> tags, moves them,1 executes them, and then removes them.

While this makes it hard to step through those scripts with a debugger, the scripts do execute.

See also

  • http://www.bennadel.com/blog/1605-jQuery-AJAX-Strips-Script-Tags-And-Inserts-Them-After-Parent-Most-Elements.htm
  • http://forum.jquery.com/topic/using-load-with-script-tags-doesn-t-work

1Either to the <head>, or the parentmost element — I haven't found an authoritative source on this yet, though I could just check the jQuery source...


Instead of using $(el).load I did a $.get, parsed the result en ev(i)lled ;) the scripts

For readibility and understanding I've tried to use variablenames that reflect their purpose and simplified it a lot. Ofcourse there should be some error handling here, but it's just a POC. HTH someone :)

Below *le code

var ajax_url = "mypage.htm";
var result_selector_filter = "#mynewcontent";
var element_to_update = $("#mycontent");

// below the statement that you'ld normally use
// element_to_update.load(ajax_url + ' ' + result_selector_filter);

$.get(ajax_url, function(response){
    // parse the entire response into a jQuery object
    var initial_parsed_result = $(response);
    // find the selector that needed to be filtered
    var result_node = initial_parsed_result.find(result_selector_filter);

    // update the html
    element_to_update.html(result_node.html());

    // variables used while looping
    var current_node,i;

    // Loop the parsed result jQuery object, check if it's a script tag and evaluate it
    for(i=0;i<initial_parsed_result.length;i++){
        // create a jquery object for current looped result html
        current_node = $(initial_parsed_result.get(i));
        // check if current node is a script tag
        // method always returns the tagname in CAPITALS
        if(current_node.prop("tagName")=="SCRIPT") {
            eval(current_node.html());
        }
    }
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜