1

I am loading an ajax response, and I need jQuery for it to make sense. I cannot load jQuery on page load due to latency reasons.

So I want to be able to load javascipt/css, whenever this ajax call is made. I read a lot of articles on this, but nothing works for me in all browsers.

I tried putting these link/script tags in the javascript response and then eval'ing the javascript in output after some time(300ms), but that does not work in chrome.(Maybe some race condition).

I also tried this:

function addJquery() {
      var script = document.createElement("script");
       script.setAttribute("src", "http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js");
      script.setAttribute('type', 'text/javascript');
      script.addEventListener('load', function() {
          var script = document.createElement("script");
          document.body.appendChild(script);
      }, false);
  document.body.appendChild(script);
}

This works in Firefox, but does not work in Chrome. I am not sure what I am doing wrong here. Can some please help, in fixing this issue?

Bulbasaur
  • 696
  • 1
  • 14
  • 22
  • The addJquery function you are trying works for me in chrome. – toofast1227 Nov 16 '12 at 16:54
  • Looks like load event is not supported for script tag in IE. Answer to this question might solve your problem - http://stackoverflow.com/questions/6725272/crossbrowser-script-load-event – toofast1227 Nov 18 '12 at 05:07

2 Answers2

0

If you load jQuery after the load event fires, there's no latency problems for you because the page is already rendered.

The load event won't fire in your case because its already occurred. Use a setInterval to detect jquery, then clear the interval.

window.addEventListener('load', function(){

    var script = document.createElement('script');
        script.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js';
    document.getElementsByTagName('head')[0].appendChild(script);

    var inter = setInterval(function(){

        if( jQuery ){
            clearInterval(inter);

            //execute jQuery code here
        }

    },100);

},false);

Also, you don't need to set the type on script elements anymore. Every browser knows that its javascript.

Geuis
  • 41,122
  • 56
  • 157
  • 219
  • I don't want to do this, as jQuery would be needed only in a few cases, when the user clicks on something and this particular ajax call is made. I don't want to load jQuery unnecessarily if its not needed.Though, I can use this piece of code in another event. Have you tried this code in chrome? Does it work? – Bulbasaur Oct 05 '12 at 05:05
  • What don't you want to do? Are you trying to load jQuery only in a specific case? – Geuis Oct 05 '12 at 05:41
0

Load the jquery file using ajax call(Make ajax async = false).

Garfield
  • 2,487
  • 4
  • 31
  • 54