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?
ICPooremanAsked:
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');
exScript.src='http://www.somedomain.com/somescript.js';
var headTag = document.getElementsByTagName('head')[0];
headTag.appendChild(exScript);


check this also http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Q_22843854.html

http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Q_22843854.html

http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Q_22901380.html

hope these helps,
kiranvj
0
 
-null-Commented:
hi

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.

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

Note however, that you would want syntactically correct javascript.
0
 
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.
0
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.