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

后端 未结 13 1729
难免孤独
难免孤独 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:53

    I ran into this where the scripts would load once, but repeat calls would not run the script.

    It turned out to be an issue with using .html() to display a wait indicator and then chaining .load() after it.

    // Processes scripts as expected once per page load, but not for repeat calls
    $("#id").html("").load("page.html");
    

    When I made them separate calls, my inline scripts loaded every time as expected.

    // Without chaining html and load together, scripts are processed as expected every time
    $("#id").html("");
    $("#id").load("page.html");
    

    For further research, note that there are two versions of .load()

    A simple .load() call (without a selector after the url) is simply a shorthand for calling $.ajax() with dataType:"html" and taking the return contents and calling .html() to put those contents in the DOM. And the documentation for dataType:"html" clearly states "included script tags are evaluated when inserted in the DOM." http://api.jquery.com/jquery.ajax/ So .load() officially runs inline scripts.

    A complex .load() call has a selector such as load("page.html #content"). When used that way, jQuery purposefully filters out script tags as discussed in articles like this one: https://forum.jquery.com/topic/the-load-function-and-script-blocks#14737000000752785 In this case the scripts never run, not even once.

提交回复
热议问题