is it possible to load js files dynamically via ajax

so I've got an html page.  I'm using some YUI scripts and using some ajax within the page.  I basically don't want to load the js files until they're needed so I was wondering if there were a way where if somebody clicked a link it could fire something that would load another javascript file in the page?

So for example some YUI library is needed for a function to execute well is it possible to include that library if the library if it wasn't included in the html when the page loaded?
Who is Participating?
Kiran Paul VJComputer EngineerCommented:
You can load a js file dynamically. For that you dont need ajax. Just simple javascript will do the trick,

this loads a javascript dynamicaly

var exScript = document.createElement('script');
var headTag = document.getElementsByTagName('head')[0];

check this also

hope these helps,

Never tried it, but I wonder if you could simply append a script tag node to the DOM, with it's source set.  I know that you can do the same with an image, and get it to load when its attached to the document.

HonorGodSoftware EngineerCommented:
I agree with null.  That is what I would try.

Note however, that you would want syntactically correct javascript.
ICPooremanAuthor Commented:
ya I've been reading up on it.  It appears that you can do what you're stating but you have to be careful with different browser implementations.

I've come across the fact that YUI has a loader utility that might be able to do what I need I'm looking into that but appreciate any other comments people have.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.