views:

72

answers:

2

The following small snippet of code cannot be changed once deployed (it's in an RIA) so everything must be loaded via a bootstrapper.js file:

<div id="someDivID"></div>
<script type="text/javascript" src="bootstrapper.js"></script>

What's the best way to load up all the js, css, and markup? Is there a better (cleaner, faster, crisper) way than the following?:

function createDivs() {
  var jsDiv = document.createElement('div');
  jsDiv.id = 'allJavascriptHere';

  var contentDiv = document.createElement('div');
  contentDiv.id = 'allContentHere';

  document.getElementById("someDivID").appendChild(jsDiv);
  document.getElementById("someDivID").appendChild(contentDiv);

  function importScript(url){
     var script = document.createElement('script');
     script.type = 'text/javascript';
     script.src = url;
     document.getElementById("jsDiv").appendChild(script);
  }

    importScript("http://example.com/jquery-1.4.2.min.js");
    importScript("http://example.com/anotherScript.js");
 }

 window.onload = function(){

   $.get("http://example.com/someHTML.html", function(data) {
      $('#contentDiv').html(data);
      setTimeout("javaScript.init()", 200);
   });
 }

with stylesheets in the someHTML.html file as so:

<style type="text/css">
   @import url("example.com/styleSheet.css");
</style>

(note: I don't know why I need the setTimeout but for some reason I do. Maybe your answer won't require it.)

+2  A: 

You can use jQuery's $.getScript() to import scripts.

I recently wrote a function to import CSS.

var getCss = function(file, callback) {

    if (typeof callback !== 'function') {
        throw 'Not a valid callback';
    };

    $.get(file, function(css) {

        var top = $('head > link[rel=stylesheet]').length ? $('head > link[rel=stylesheet]:last') : $('head > *:last'); 

        top.after('<link rel="stylesheet" type="text/css" href="' + file + '">');

        callback();

    });


};
alex
Thanks @alex! What's the point of getting `css` without using it? I.e., why the ajax call?
Emile
@Emile Just to preload it, so when I link to it, I know it has been downloaded and can call the callback. If I placed the CSS received between `<style>` tags, then the relative URLs would be wrong. Sure I could probably fix them with regex, but I find this way easier :)
alex
Thanks for the follow-up!
Emile
@Emile No worries, and damn, I've hit the rep cap! Haha. :D
alex
@Alex ...and just 200 to go till the big 20. Good on ya!
Emile
A: 

If your css is also in that js file, you can simply add css code to the documents style tag. It can be useful in some situations, where using different css file is not allowed etc.

Bick