Import JavaScript file in JavaScript function [duplicate]

Possible Duplicates:
Include a JavaScript file in a JavaScript file
How to include a JavaScript file in another JavaScript file?

What is the best way to import a JavaScript file, for example file.js, in a JavaScript function()?

For example, what is the best way to replace the todo statement:

function doSomething() {
   if (xy.doSomething == undefined) {
      // TODO: load 'oldVersionPatch.js'

Possibly the best solution is to create script element and add it into the HTML page.

  • Is it better to add/append it into head, or body (what will load when)?
  • Is it better to use JavaScript or jQuery (what is more cross-browser compatible)?


  this.__defineGetter__("__FILE__", function() {
    return (new Error).stack.split("\n")[2].split("@")[1].split(":").slice(0,-1).join(":");

  this.__defineGetter__("__DIR__", function() {
    return __FILE__.substring(0, __FILE__.lastIndexOf(""));

function include(file,charset) {
    if (document.createElement && document.getElementsByTagName) {
        var head = document.getElementsByTagName('head')[0];
        var script = document.createElement('script');
        script.setAttribute('type', 'text/javascript');
        script.setAttribute('src', __DIR__ + "" + file);
            script.setAttribute('charset', charset);

  var filename="oldVersionPatch.js";
  var js = document.createElement('script');
  js.setAttribute("src", filename);

.. should do it

Very simply, in JavaScript create a <script> element, append the src attribute with whatever the URL is and attach to the DOM. That should do it.

You have to make your code asynchronous to gain this:

var script = document.createElement('script');
script.src = yourJavascriptFileLocation;
script.onload = script.onreadystatechange = function() {
    if (!script.readyState || script.readyState === 'complete') {
        /* Your code rely on this JavaScript code */
var head = document.getElementsByTagName('head')[0];
// Don't use appendChild
head.insertBefore(script, head.firstChild);

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .
Read More:   The create-react-app imports restriction outside of src directory

Similar Posts