Yes, you can do that. I'll bet the reason you're getting $ undefined is that
you're trying to reference it immediately after running that code. The
dynamic script element loads asynchronously, and as with all asynchronous
JavaScript, you need to either use a completion callback function or a
setInterval polling loop. The callback is a much better way to go.

I don't think jQuery provides this "out of the box", but it's easy to add to
your own copy of jQuery. Simply add a line like this at the very end of the
file:

    window.jQueryLoaded && jQueryLoaded();

And define a jQueryLoaded function in your code:

    function jQueryLoaded() {
        $(function() {
            // go to town here!
        });
    }

Here's a working test case:

http://mg.to/test/jquery/dynamic/jquery-dynamic.html

-Mike

> From: jQuery(new).to(me)
> 
> Hello,
> 
> I am trying to load jQuery from Javascript like the following code.
> 
> 
> == code ==
> if (typeof jQuery == 'undefined' || !jQuery) {
>       var s = document.createElement('script');
>       s.setAttribute('type','text/javascript');
>       s.setAttribute('src','http://localhost/jquery-latest.min.js');
>       document.getElementsByTagName('head')[0].appendChild(s);
> }
> == end of code ==
> 
> However, then this code is included, "jquery-latest.min.js" 
> is included, but the page shows javascript error, "$ is not defined."
> 
> Any tips to solve this problem??
> 
> Thanks bunch in advance!

Reply via email to