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

Using Javascript to load other external Javascripts - Stack Overflow

programmeradmin2浏览0评论

I have a library of JS code to load from a folder. Instead of typing the <script src='...'></script> lines one by one in the tag of the HTML document, is there a way of just link one Javascript file which organizes and automatically load other javascript files.

I know the Dojotoolkit is using this technique where only one JS file is loaded onto the client's puter, and once the code has been requested in the browser, 20 other JS code each with <script> tag are generated.

I have a library of JS code to load from a folder. Instead of typing the <script src='...'></script> lines one by one in the tag of the HTML document, is there a way of just link one Javascript file which organizes and automatically load other javascript files.

I know the Dojotoolkit is using this technique where only one JS file is loaded onto the client's puter, and once the code has been requested in the browser, 20 other JS code each with <script> tag are generated.

Share Improve this question edited Aug 13, 2012 at 10:11 Aurelio De Rosa 22.2k8 gold badges50 silver badges71 bronze badges asked Aug 28, 2010 at 12:42 Dennis DDennis D 1,3434 gold badges17 silver badges24 bronze badges 3
  • Google for LabJS and RequireJS. – Pointy Commented Aug 28, 2010 at 12:46
  • duplicate: stackoverflow./questions/21294/… – ankitjaininfo Commented Aug 28, 2010 at 12:47
  • Not duplicate, other question is for the Prototype framework. This one is for vanilla javascript. – balupton Commented Aug 28, 2010 at 12:58
Add a ment  | 

3 Answers 3

Reset to default 5

This is the code you need:

    // Create
    var bodyEl = document.body;
    var scriptEl = document.createElement('script');
    scriptEl.type = 'text/javascript';
    scriptEl.src = url;
    bodyEl.appendChild(scriptEl);

Put that into a function, have an array of all the javascript files, and call that function for each file.

Benefits of using the DOM is that document.write doesn't work in some funny instances. More about this here: document.write() vs inserting DOM nodes: preserve form information?

Code taken from the open source project jQuery Sparkle: http://github./balupton/jquery-sparkle/blob/master/scripts/resources/jquery.appendscriptstyle.js#L103

A simple way to do that:

document.write("<script type='text/javascript' src='b.js'></script>"); 

Try use requireJs, he have very userful functions

Official website

发布评论

评论列表(0)

  1. 暂无评论