tags:

views:

399

answers:

4

Hey,

Say my javascript scripts aren't embedded in html/xml... I want to write a small library of helper functions to use in my scripts. Obviously there has to be an "#include" or "require" keyword in javascript, but I can't find any. Anything I could with Google relies on the code being part of html/xml, which doesn't help in my case. What should I do?

Thanks!

A: 

to include a js file in html:

<script type="text/javascript" src="..."></script>

it should be in the page head for correctness.

marcus.greasly
You can have the javascript write one of these in the head too.
Daniel A. White
Thanks but that's not what I meant at all. I have a .js file which I used outside of any html code. It's not for the web at all. Now I want to import another .js file into mine. How do I do that?
marcus.greasly
+1  A: 

There actually isn't a really #include or require in javascript. You're actually supposed to handle all the dependencies yourself. I've seen people do a hack where they do a document.write to include other javascript files.

smack0007
+16  A: 

I believe you mean to write some sort of dependency tracking framework for your javascript files and use a process called "Lazy-Loading" to load the required JS file only when it's needed.

Check out Using.js, it seems to do what you need.

Also you might want to check addModule from YUILoader. It allows loading non-YUI framework components on the fly.

Razvan Caliman
Thanks!! Using.js sounds good.
you must include Using.js first!
dfa
A: 

in the case you care, here there is a version of include that uses the document object via it's DOM interface:

function include(aFilename) {
     var script = document.createElement('script');
     script.src = aFilename;
     script.type = 'text/javascript';
     document.getElementsByTagName('head')[0].appendChild(script)
}

the problem is that you must include this function in all your source file that needs includes... :P :P

dfa
aFilename not referenced from within the script. And how is this helpful?
Peter Perháč