jQuery.load() - Inside External Javascript
i load an external page with
$('#myContainer').load('myfile.html');
in myfile.html theres an
<script type="text/javascript" src="otherscript.js"></script>
Some users report that the otherscript.js is not loaded... i've tested a all common browsers (firefox, ie 6/7, safari, opera etc.) - i cant figure out why th开发者_Python百科is wont work...
an other think is... according to my firebug the browser wont cache the otherscript.js.. it loads with
otherscript.js?_=1234785
(timestamp here :) )
Anyone has an idea why some browsers doesnt support that and.. how can i enable that caching?
MFG Christopher
The .load functions only loads html. Since you are not allowed to load external scripts in to the browser by the browser security protocol. But luckily there's .getScript to get around this. Check it out: http://docs.jquery.com/Ajax/jQuery.getScript
..fredrik
to avoid problems with the cache, you can do the following:
$('#myContainer').load('myfile.html?'+(new Date()).getTime());
in myfile.html:
<script type="text/javascript">
var script = document.createElement("script");
script.setAttribute('type','text/javascript');
script.setAttribute('src','otherscript.js?'+(new Date()).getTime());
document.body.appendChild(script);
</script>
accommodating this code to your need.
As fredrik pointed out, .load does not load external files, however it will pass the result to html to execute any javascript that's there.
I had a similar issue and I came up with this solution that extracts any script tags from the results that have a src attribute, then use $.getScript to load the attribute value.
$('#exmple').load(url, function(result) {
$(result).filter('script[src]').each(function () {
var script = $(this).attr('src');
$.getScript(script);
});
});
精彩评论