如何将一个js文件包含到另一个js文件中,以便坚持DRY principle并避免重复代码。
最佳答案
您只能将脚本文件包含在 HTML 页面中,而不能包含在另一个脚本文件中。也就是说,您可以编写将“包含”脚本加载到同一页面中的 JavaScript:
var imported = document.createElement('script');
imported.src = '/path/to/imported/script';
document.head.appendChild(imported);
您的代码很有可能取决于您的“包含”脚本,但在这种情况下,它可能会失败,因为浏览器会异步加载“导入”脚本。最好的办法是简单地使用第三方库,例如 jQuery 或 YUI,它可以为您解决这个问题。
// jQuery
$.getScript('/path/to/imported/script.js', function()
{
// script is now loaded and executed.
// put your dependent JS here.
});
关于javascript - 如何将 js 文件包含在另一个 js 文件中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4634644/