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?
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?
Share Improve this question edited Nov 10, 2011 at 19:25 Lightness Races in Orbit 385k77 gold badges664 silver badges1.1k bronze badges asked Apr 18, 2009 at 12:51 BuliBuli 4 |4 Answers
Reset to default 17I 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.
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.
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
to include a js file in html:
<script type="text/javascript" src="..."></script>
it should be in the page head for correctness.
document
is not defined in this context. – BrainSlugs83 Commented Jan 23, 2014 at 0:31