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 loaded page 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>
Pay attention to the css attribute in the script tag - it indicates the stylesheet related 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, a stylesheet that simply colors the inner div that loads, as proof that it all works:
- plugin.css -
#inner { border: solid 1px blue; }
now you will notice how the stylesheet loads: we look at $('script') and select the latter, then we get the css attribute and attach the link element to the document chapter.
I can visit /svc.html , and javascript starts, loads my style, everything is cool - however, if I visit /main.html , javascript starts, but does not find the plugin.js load in the $('script') array (and, therefore, the stylesheet does not load). Please note that the script plugin starts, it just does not see itself.
This is mistake? jQuery AJAX method limitation? should $('script') display all loaded scripts?
* edit *
after a lot of crying and gnashing of teeth, I decided to go for a Kevin B solution, however I canβt get it to work, mainly because the plugin.js code plugin.js started when scriptNode , but in the plugin code the node is not yet inserted and therefore not accessible in the $('script') array, so I'm still SOL. I put all the code for the review here:
http://www.arix.com/tmp/loadWithJs/