suppose you have a simple web page that dynamically loads content that looks like this:
- main.html -
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript"
src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-1.6.2.js">
</script>
<script type="text/javascript">
$(function() {
$.ajax({
type: 'get', cache: false, url: '/svc.html',
success: function(h) {
$('#main').html(h);
}
});
});
</script>
</head>
<body>
<div id='main'>
loading...
</div>
</body>
</html>
and that the page it loads uses a little Javascript in a separate file:
- svc.html -
<script type="text/javascript"
src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-1.6.2.js">
</script>
<script type="text/javascript" src="/plugin.js" css="/plugin.css"></script>
<div id='inner'>
dynamically loaded content
</div>
notice the css
attribute on the script tag - it indicates a style-sheet that belongs to the script and which the script will load for us. Here's the script:
- plugin.js -
var css = $('<link />', {
rel: "stylesheet", type: "text/css", href: $('script:last').attr('css')
});
$('head').append(css);
and, finally, the style-sheet, which merely colours the inner
div that gets loaded, as proof that it all works:
- plugin.css -
#inner
{
border: solid 1px blue;
}
now, you'll notice the way the style-sheet gets loaded: we look at $('script')
and pick off the last one, then we grab the css
attribute and attach a link
item to the head of the document.
I can visit /svc.html
and the javascript runs, loads my style-sheet, all's cool - however, if I visit /main.html
, the javascript runs but fails to find the loading of the plugin.js
in the array of $('script')
(and therefore fails to load the stylesheet). Note that the plugin script does run, it just doesn't see itself.
Is this a bug? a limitation of the jQuery AJAX method? shouldn't $('script')
reflect all scripts that have been loaded?
* edit *
after much wailing and gnashing of teeth, I decided to go for Kevin B's solution, however, I can't get it to work, basically because the plugin.js
code runs at the time the scriptNode
gets inserted, but within the plugin code, the node has not yet been inserted and is thus not available in the $('script')
array - so I'm still SOL. I've put all the code for review here:
http://www.arix.com/tmp/loadWithJs/
See Question&Answers more detail:
os