2

可能重复:
在 JavaScript 文件中包含 JavaScript 文件?

有没有办法简单地将 JavaScript 库导入 JavaScript 文件?

在 Python 中,您可以简单地执行以下操作:

import math

JavaScript中有类似的东西吗?

4

2 回答 2

4

In today's vanilla javascript, no, you can't do that.

But in a future version, a similar feature will probably be available. Modules are discussed from a long time. And as a Python programmer, you might be interested by this article too.

Today you may

  • use one of the many frameworks enabling this kind of import, like require.js.
  • dynamically add a <script> element to your page (yes, it's ugly)
  • fetch it using ajax and evaluating it (it's uglier)

But...

if you always import the same files, you should consider concatenating them (and minifying them), as the number of requested files is one of the main elements to consider when optimizing the performances of your site.

于 2013-01-02T15:42:04.163 回答
0

你可以看看这个问题(以及答案......):如何在另一个 JavaScript 文件中包含一个 JavaScript 文件?

我特别喜欢 jQuery 的getScript()函数:

$.getScript("my_lovely_script.js", function(){
   alert("Script loaded and executed.");
   // here you can use anything you defined in the loaded script
});
于 2013-01-02T15:45:44.453 回答