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?
4 Answers
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.
3 Comments
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
2 Comments
to include a js file in html:
<script type="text/javascript" src="..."></script>
it should be in the page head for correctness.
documentis not defined in this context.