Javascript – How to import a variable from another JavaScript file

htmljavascriptjquery

I want to import an array (imageArray[]) that is being populated by another JavaScript file (imageUploadDisplay.js) into another JavaScript file function (postInfoAndImages.js). Below is my imageUploadDisplay.js function that I tried to use.

// In my imageUploadDisplay.js

var imageList = [];

function myImageList() {

    return imageList;
}

As explained by others I use the following jQuery to import imageUploadDisplay.js into the JavaScript postInfoAndImages.js:

// In my postInfoAndImages.js
var imageList = [];

$.getScript('imageUploadDisplay.js', function () {
            // Script is now loaded and executed.
            alert("Script loaded, but not necessarily executed.");
            imageList = myImageList(); // Picture array
            console(imageList);
        });

Best Solution

For modern browsers like Firefox, Chrome, Safari and Opera, just use ES6 modules.

In your imageUploadDisplay.js create a named export:

// imageUploadDisplay.js
var imageList = [];

export function myImageList() {
  return imageList;
}

Then just import the function:

// then in postInfoAndImages.js
import { myImageList } from './path/to/imageList.js';

var imageList = myImageList();

In your HTML, you no longer need to include imageUploadDisplay.js (this is done by the import at runtime).

Instead, include the importing script with type="module":

<script type="module" src="./path/to/postInfoAndImages.js"></script>