jQuery .load() call doesn't execute JavaScript in loaded HTML file

后端 未结 13 1866
难免孤独
难免孤独 2020-11-22 08:28

This seems to be a problem related to Safari only. I\'ve tried 4 on Mac and 3 on Windows and am still having no luck.

I\'m trying to load an external HTML file and

13条回答
  •  日久生厌
    2020-11-22 08:54

    If you want to load both the HTML and scripts, here's a more automated way to do so utilizing both $(selector).load() and jQuery.getScript(). This specific example loads the HTML content of the element with ID "toLoad" from content.html, inserts the HTML into the element with ID "content", and then loads and runs all scripts within the element with the "toLoad" ID.

    $("#content").load("content.html #toLoad", function(data) {
        var scripts = $(data).find("script");
    
        if (scripts.length) {
            $(scripts).each(function() {
                if ($(this).attr("src")) {
                    $.getScript($(this).attr("src"));
                }
                else {
                    eval($(this).html());
                }
            });
        }
    
    });
    

    This code finds all of the script elements in the content that is being loaded, and loops through each of these elements. If the element has a src attribute, meaning it is a script from an external file, we use the jQuery.getScript method of fetching and running the script. If the element does not have a src attribute, meaning it is an inline script, we simply use eval to run the code. If it finds no script elements, it solely inserts the HTML into the target element and does not attempt to load any scripts.

    I've tested this method in Chrome and it works. Remember to be cautious when using eval, as it can run potentially unsafe scripts and is generally considered harmful. You might want to avoid using inline scripts when using this method in order to avoid having to use eval.

提交回复
热议问题