Search code examples
javascriptvariablesdynamic-data

Javascript : How to get value of variable from specific file from 2 different file?


I have 1 page that load Js file from another server. Its load file for each product in e-commerce store with its id in url see below structure.

Product 1: http://static.www.xxx.com/mydata/uXKojYEd9WXFpAasite/v4_3/1/d/itemjs

Product 2:

http://static.www.xxx.com/mydata/uXKojYEd9WXFpAasite/v4_3/2/d/itemjs

Product 3:

http://static.www.xxx.com/mydata/uXKojYEd9WXFpAasite/v4_3/3/d/itemjs

All Js files contain code like below

var MyItemData={"counts":{"q":1,"a":1,"r":2,"ar":4,"rr":0,"dq":1,"da":1,"c":0,"sdsd":0},"active":true};

Now I am reading this data in Html like below

var mycounta = MyItemData.counts.a;
    var mycountq = MyItemData.counts.q;
    var mycountr = MyItemData.counts.r;

The problem here is I can only get data for last product as variable MyItemData is the same for all files. I've to read each files by id but i don't know proper way to achieve it. does anyone tried something like this?


Solution

  • You can loop the answer below which loads external js file dynamically.

    How do I load a javascript file dynamically?

    On each iteration, read MyItemData and use it.

    By using the function loadJS on above link;

    <script type="application/javascript">
    var listOfJSFiles=["http://static.www.xxx.com/mydata/uXKojYEd9WXFpAasite/v4_3/1/d/itemjs", "http://static.www.xxx.com/mydata/uXKojYEd9WXFpAasite/v4_3/2/d/itemjs", "http://static.www.xxx.com/mydata/uXKojYEd9WXFpAasite/v4_3/3/d/itemjs"];
    var listOfMyItemData=[];
    
    function loadJS(file) {
        // DOM: Create the script element
        var jsElm = document.createElement("script");
        // set the type attribute
        jsElm.type = "application/javascript";
        // make the script element load file
        jsElm.src = file;
        // finally insert the element to the body element in order to load the script
        document.body.appendChild(jsElm);
    }
    
    var arrayLength = listOfJSFiles.length;
    for (var i = 0; i < arrayLength; i++) {
        loadJS(listOfJSFiles[i]);
        listOfMyItemData.push(MyItemData);
        //removing listOfJSFiles[i] from html is recommended.
    }
    
    </script>