Load()调用不会在加载的 HTML 文件中执行 JavaScript

这个问题似乎只与 Safari 有关。我在 Mac 和 Windows 上分别试了4次和3次,仍然没有结果。

我试图加载一个外部的 HTML 文件并执行嵌入的 JavaScript。

我要用的代码是这样的:

$("#myBtn").click(function() {
$("#myDiv").load("trackingCode.html");
});

trackingCode.html看起来像这样(现在很简单,但是会展开一次/如果我让它工作的话) :

<html>
<head>
<title>Tracking HTML File</title>
<script language="javascript" type="text/javascript">
alert("outside the jQuery ready");
$(function() {
alert("inside the jQuery ready");
});
</script>
</head>


<body>
</body>
</html>

我在 IE (6 & 7)和 Firefox (2 & 3)中都看到了提醒消息。然而,我不能看到在 Safari (最后一个浏览器,我需要关注-项目需求-请没有火焰战争)的消息。

对于 Safari 为什么忽略 trackingCode.html文件中的 JavaScript 有什么想法吗?

最终,我希望能够将 JavaScript 对象传递给这个 trackingCode.html文件,以便在 jQuery 准备调用中使用,但是我希望在这样做之前确保这在所有浏览器中都是可能的。

214792 次浏览

You are loading an entire HTML page into your div, including the html, head and body tags. What happens if you do the load and just have the opening script, closing script, and JavaScript code in the HTML that you load?

Here is the driver page:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jQuery Load of Script</title>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("jquery", "1.3.2");
</script>
<script type="text/javascript">
$(document).ready(function(){
$("#myButton").click(function() {
$("#myDiv").load("trackingCode.html");
});
});
</script>
</head>
<body>
<button id="myButton">Click Me</button>
<div id="myDiv"></div>
</body>
</html>

Here is the contents of trackingCode.html:

<script type="text/javascript">
alert("Outside the jQuery ready");
$(function() {
alert("Inside the jQuery ready");
});
</script>

This works for me in Safari 4.

Update: Added DOCTYPE and html namespace to match the code on my test environment. Tested with Firefox 3.6.13 and example code works.

Test with this in trackingCode.html:

<script type="text/javascript">


$(function() {


show_alert();


function show_alert() {
alert("Inside the jQuery ready");
}


});
</script>

I realize this is somewhat of an older post, but for anyone that comes to this page looking for a similar solution...

http://api.jquery.com/jQuery.getScript/

jQuery.getScript( url, [ success(data, textStatus) ] )
  • url - A string containing the URL to which the request is sent.

  • success(data, textStatus) - A callback function that is executed if the request succeeds.

$.getScript('ajax/test.js', function() {
alert('Load was performed.');
});

Well I had the same problem that only seemed to happen for Firefox, and I couldn't use another JQuery command except for .load() since I was modifying the front-end on exisitng PHP files...

Anyways, after using the .load() command, I embedded my JQuery script within the external HTML that was getting loaded in, and it seemed to work. I don't understand why the JS that I loaded at the top of the main document didn't work for the new content however...

This doesn't seem to work if you're loading the HTML field into a dynamically created element.

$('body').append('<div id="loader"></div>');
$('#loader').load('htmlwithscript.htm');

I look at firebug DOM and there is no script node at all, only the HTML and my CSS node.

Anyone have come across this?

I wrote the following jquery plugin for html loading function: http://webtech-training.blogspot.in/2010/10/dyamic-html-loader.html

$("#images").load(location.href+" #images",function(){
$.getScript("js/productHelper.js");
});

You've almost got it. Tell jquery you want to load only the script:

$("#myBtn").click(function() {
$("#myDiv").load("trackingCode.html script");
});

A other version of John Pick's solution just before, this works fine for me :

jQuery.ajax({
....
success: function(data, textStatus, jqXHR) {
jQuery(selecteur).html(jqXHR.responseText);
var reponse = jQuery(jqXHR.responseText);
var reponseScript = reponse.filter("script");
jQuery.each(reponseScript, function(idx, val) { eval(val.text); } );
}
...
});

I was able to fix this issue by changing $(document).ready() to window.onLoad().

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("<img src=wait.gif>").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("<img src=wait.gif>");
$("#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.

Tacking onto @efreed answer...

I was using .load('mypage.html #theSelectorIwanted') to call content from a page by selector, but that means it does not execute the inline scripts inside.

Instead, I was able to change my markup so that '#theSelectorIwanted'became it's own file and I used

load('theSelectorIwanted.html`, function() {});

and it ran the inline scripts just fine.

Not everyone has that option but this was a quick workaround to get where I wanted!

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.