JavaScript equivalent to Python's import?

Possible Duplicate:
Include JavaScript file inside JavaScript file?

Is there any way to simply import a JavaScript library into a JavaScript file?

In Python, you can simply do this:

import math

Is there anything similar in JavaScript?


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.


    You can have a look at this question (and the answers as well...) : How do I include a JavaScript file in another JavaScript file?

    I especially like the getScript() function of jQuery :

    $.getScript("my_lovely_script.js", function(){
       alert("Script loaded and executed.");
       // here you can use anything you defined in the loaded script
    });
    
    链接地址: http://www.djcxy.com/p/7348.html

    上一篇: 我如何将.js链接包含到另一个.js中?

    下一篇: 等同于Python导入的JavaScript?