使用Javascript加载其他外部Javascripts [英] Using Javascript to load other external Javascripts

查看:86
本文介绍了使用Javascript加载其他外部Javascripts的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JS代码库,可以从文件夹加载。
而不是在HTML文档的标记中逐个输入< script src ='...'>< / script> 行,有没有办法只链接一个Javascript文件,组织并自动加载其他javascript文件。

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.

我知道Dojotoolkit正在使用这种技术只加载一个JS文件客户端的计算机,一旦在浏览器中请求了代码,就会生成20个其他JS代码,每个代码都带有< script> 标记。

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

推荐答案

这是您需要的代码:

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

把它放到一个函数中,有一个包含所有javascript文件的数组,并为每个调用该函数文件。

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

使用DOM的好处是document.write在一些有趣的实例中不起作用。有关这方面的更多信息:
document.write() vs插入DOM节点:保留表单信息?

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?

从开源项目获取的代码jQuery Sparkle:
http://github.com/balupton/jquery-sparkle/blob/ master / scripts / resources / jquery.appendscriptstyle.js#L103

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

这篇关于使用Javascript加载其他外部Javascripts的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆