如何在另一个js文件中包含js文件? [英] How to include js file in another js file?

查看:529
本文介绍了如何在另一个js文件中包含js文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

在.js文件中包含.js文件

如何将js文件包含到另一个js文件中,以便坚持 DRY原则并避免重复代码。

How can I include a js file into another js file , so as to stick to the DRY principle and avoid duplication of code.

推荐答案

您只能在HTML页面中包含脚本文件,不在另一个脚本文件中。也就是说,你可以编写JavaScript,将你的包含脚本加载到同一页面中:

You can only include a script file in an HTML page, not in another script file. That said, you can write JavaScript which loads your "included" script into the same page:

var imported = document.createElement('script');
imported.src = '/path/to/imported/script';
document.head.appendChild(imported);

您的代码很可能取决于您的包含脚本,但在这种情况下,它可能会失败,因为浏览器将异步加载导入脚本。你最好的选择就是简单地使用像jQuery或YUI这样的第三方库,它可以解决这个问题。

There's a good chance your code depends on your "included" script, however, in which case it may fail because the browser will load the "imported" script asynchronously. Your best bet will be to simply use a third-party library like jQuery or YUI, which solves this problem for you.

// jQuery
$.getScript('/path/to/imported/script.js', function()
{
    // script is now loaded and executed.
    // put your dependent JS here.
});

这篇关于如何在另一个js文件中包含js文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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