2

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?

Community
  • 1
  • 1
Games Brainiac
  • 80,178
  • 33
  • 141
  • 199

2 Answers2

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.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • What is this vanilla javaScript? – Games Brainiac Jan 02 '13 at 15:48
  • 1
    The standard, framework and library free, version of javascript : http://vanilla-js.com/ ("vanilla something" is an expression meaning the basic flavour of something). – Denys Séguret Jan 02 '13 at 15:49
  • Thanks. Sorry, I thought it was a version of javaScript that you have to download elsewhere. I mean can you blame me? Apples and blackberries are devices now....Alas, the world used to be much simpler! :D – Games Brainiac Jan 02 '13 at 15:53
  • Don't be sorry because you don't know this expression. If you're not a native speaker, this isn't trivial at all. – Denys Séguret Jan 02 '13 at 15:55
  • I am native! :P I just don't know what is what anymore. I mean there is a javaScript library called backbone...what next? Oesophagus? lol... – Games Brainiac Jan 02 '13 at 15:56
0

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
});
Community
  • 1
  • 1
clement g
  • 461
  • 1
  • 3
  • 10
  • The funny thing is I am trying to load jQuery through an import statement! :P But, I guess that won't work. You just have to add it before the javaScript file before you incorporate it into your HTML. – Games Brainiac Jan 02 '13 at 15:47