Buli
Buli

Reputation:

How to #include in javascript?

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?

Upvotes: 7

Views: 6284

Answers (4)

dfa
dfa

Reputation: 116352

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

Upvotes: 0

Razvan Caliman
Razvan Caliman

Reputation: 4623

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.

Upvotes: 17

smack0007
smack0007

Reputation: 11366

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.

Upvotes: 3

marcus.greasly
marcus.greasly

Reputation: 703

to include a js file in html:

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

it should be in the page head for correctness.

Upvotes: -2

Related Questions