views:

493

answers:

3
+1  Q: 

Load jQuery, wait

I need to dynamically load jQuery and jQuery UI from a javascript, then check if it has loaded and do something afterwards.

function loadjscssfile(filename, filetype){
 if (filetype=="js"){ //if filename is a external JavaScript file

  var fileref=document.createElement('script');
  fileref.setAttribute("type","text/javascript");
  fileref.setAttribute("src", filename);
 }
 else if (filetype=="css"){ //if filename is an external CSS file
  var fileref=document.createElement("link");
  fileref.setAttribute("rel", "stylesheet");
  fileref.setAttribute("type", "text/css");
  fileref.setAttribute("href", filename);
 }
 if (typeof fileref!="undefined")
  document.getElementsByTagName("head")[0].appendChild(fileref);
}


loadjscssfile("http://localhost/js/jquery-1.3.2.min.js", "js");
loadjscssfile("http://localhost/js/jquery-ui-1.7.2.custom.min.js", "js");

I have done some research and found that I need to either use a callback or a settimeout. Trouble is I'm really new in javascript and it's really giving me a hard time. Can anyone set me in the right direction please?

A: 

I haven't tried this, but I'm pretty sure that if you call the loadjscssfile function first, and then add

$(document).ready(function() {
    //Everything in here will be called after jQuery is ready
});

should work.

peirix
if jQuery hasn't been loaded yet, I don't think you can use the `$` method at all
Tobias Cohen
this was behind my original logic but javascript does not wait for jquery to load THEN gets to the rest it just parses the entire script and does everything.
Carvefx
+2  A: 

I've never had to do this myself, but presumably you could just use a repeating timeout to check for presence of the needed objects:

function jqueryLoaded() {
    //do stuff
}

function checkJquery() {
    if (window.jQuery && jQuery.ui) {
        jqueryLoaded();
    } else {
        window.setTimeout(checkJquery, 100);
    }
}

checkJquery();
Tobias Cohen
this was exactly what i'm looking for. Trouble is, for some reason it doesn't loop. I'm checking it via firebug and it definetly adds everything I need. If I click the bookmarklet again, it works. My conclusion is that it doesn't loop.function checkJquery() { if (jQuery().dialog) { jqueryLoaded(); } else { window.setTimeout("100", checkJquery); }}checkJquery();
Carvefx
A: 

I'm pretty sure that the window.onload() function should trigger when all scripts are loaded. And you don't need to bind stuff to the 'ready' event in jQuery.

loadjscssfile("http://localhost/js/jquery-1.3.2.min.js", "js");
loadjscssfile("http://localhost/js/jquery-ui-1.7.2.custom.min.js", "js");

window.onload = function() {
    if(window.jQuery && jQuery.ui) {
        alert('loaded');
    }
}
David
this does not work at all. The first version was closer to working. Thanks for the help though!
Carvefx