1

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?

Kul
  • 378
  • 12
  • 20

2 Answers2

1

Provided that you are loading those files using script tag. You could create an array to hold items and intermix script tags with inline scripts that save current value of MyItemData inside the array.

<script>
    var items = [],
        addItem = function() {
           items.push(MyItemData)
        };
</script>

Then call addItem after each script or play with onload event (not sure if the later would work).

<script 
src="http://static.www.xxx.com/mydata/uXKojYEd9WXFpAasite/v4_3/1/d/itemjs"
>
</script>

<script>addItem()</script>

<script 
src="http://static.www.xxx.com/mydata/uXKojYEd9WXFpAasite/v4_3/2/d/itemjs"
>
</script>

<script>addItem()</script>

etc.

Yury Tarabanko
  • 44,270
  • 9
  • 84
  • 98
1

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>
yılmaz
  • 1,818
  • 13
  • 15
  • file is already loading on page. but `MyItemData` only takes data from last file. I've loop to load files per product. – Kul Jun 01 '17 at 13:04