Can you load a Library from inside a JS?

Hi all,

I was wondering if it is possible to call a Library, say Prototype or jQuery from within a javascript file?

The reason I ask is that often when I write Widgets for clients then want me to provide them with a single Javascript link to embed in a webpage.

Ideally id like to be able to call in a library, then run a block of code all from a single file.

Is this possible?

Kind regards,

Matt

Yes, you can manipulate the DOM by adding a script tag to the header while or after the page loads.

Something like this, found on Google:


var oHead = document.getElementsByTagName('HEAD').item(0);
var oScript= document.createElement("script");
oScript.type = "text/javascript";
oScript.src="other.js";
oHead.appendChild( oScript);

That works great loading the script in - but for some reason non of my code based on the prototype library works if I load things that way.

Maybe the prototype based code isn’t being fired properly because of the late-loading of the library.
All code depending on the library should be loaded after the library. Perhaps there’s some documentation on the Prototype site detailing this kind of late-loading?

Yes thats my thinking, im pretty sure the prototype library is loading AFTER my code so I will see what I can dig up.

Thanks for all your help!

If you need to your libraries and such dynamically using JavaScript a great way i have found to do it is to use a small API called Require.JS, basically it loads a list of files you specify in an array and only runs an anonymous function you pass to it once all the libraries have finished loading.

You can read more about it here http://requirejs.org/