jQuery .load()调用未在加载的HTML文件中执行JavaScript


83

这似乎仅与Safari有关。我在Mac上尝试过4,在Windows上尝试过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 ready调用中使用,但是我想确保在所有浏览器中都可以做到这一点。

Answers:


56

您正在将整个HTML页面加载到div中,包括html,head和body标签。如果执行加载,并且在加载的HTML中仅包含打开脚本,关闭脚本和JavaScript代码,会发生什么情况?

这是驱动程序页面:

<!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.


1
Got it, thanks Tony! Removing the <html>, <head> and <body> tags seemed to do the trick.
Mike

1
i was wandering whether i should do a seperate ajax call getJson() because i heard of this.. But if it works like that it is ok!! I would call the same queries twice otherwise
GorillaApe

2
Your code is not actually working in FF (IE8 - working fine). Is there a way to make this work in all the browsers? Thanks

1
@Maxim Galushka I still had these files in my personal workstation. Without modification, they produced the correct behavior. I am using Firefox 3.6.13 on Windows 7.
Tony Miller

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

This did the trick for me. Here is an example that you can try: var frmAcademicCalendar = "frmAcademicCalendar.aspx" if (window.location.href.toLowerCase().indexOf(frmAcademicCalendar.toLowerCase()) >= 0) { $("#IncludeCMSContent").load("example.com #externalContent",function() { $.getScript("example.js"); }); }
Evan

25

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); } );
   }
   ...
});

2
This is the best solution!, I love you @Yannick, you made my day
utiq

15

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.');
});

11

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 had to load the html, then in the callback, use $.getScript to get the javascript.
Dex

1
Dude! You solved my problem about 8 years earlier. Thanks :D
Skorek

3

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

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

7
But this seems to ONLY load and the script. How do you get it to load the html content AND run any javascript it might contain?
ThatAintWorking


2

Test with this in trackingCode.html:

<script type="text/javascript">

    $(function() {

       show_alert();

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

    });
 </script>

1

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.


0

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...


Easy, because the new content was not there when the script got executed.
Matteo

0

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


0

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!

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.