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 have the JavaScript that is embedded execute.
The code I'm trying to use is this:
$("#myBtn").click(function() {
$("#myDiv").load("trackingCode.html");
});
trackingCode.html
looks like this (simple now, but will expand once/if I get this working):
<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>
I'm seeing both alert messages in IE (6 & 7) and Firefox (2 & 3). However, I am not able to see the messages in Safari (the last browser that I need to be concerned with - project requirements - please no flame wars).
Any thoughts on why Safari is ignoring the JavaScript in the trackingCode.html
file?
Eventually I'd like to be able to pass JavaScript objects to this trackingCode.html
file to be used within the jQuery ready call, but I'd like to make sure this is possible in all browsers before I go down that road.
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...
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:
Here is the contents of trackingCode.html:
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.
You've almost got it. Tell jquery you want to load only the 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/
A other version of John Pick's solution just before, this works fine for me :