Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I import a variable from another JavaScript file?

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);
        });
like image 556
Thabiso Prosper Ramokopu Avatar asked Mar 17 '26 05:03

Thabiso Prosper Ramokopu


1 Answers

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>
like image 153
connexo Avatar answered Mar 20 '26 05:03

connexo