最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to #include in javascript? - Stack Overflow

programmeradmin1浏览0评论

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
  • What do you need to embed/require? – James Commented Apr 18, 2009 at 12:55
  • A .js file with several functions... I want to use these functions in other .js files. – Buli Commented Apr 18, 2009 at 12:56
  • What's wrong with function load(src){var s = document.createElement('script'); s.src = src; document.body.appendChild(s);} – James Commented Apr 18, 2009 at 13:21
  • @James he's not using HTML / XML. There is no DOM. document is not defined in this context. – BrainSlugs83 Commented Jan 23, 2014 at 0:31
Add a comment  | 

4 Answers 4

Reset to default 17

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.

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.

发布评论

评论列表(0)

  1. 暂无评论