Retrieving JSON data taking too long?

Hi all.
So I have this frontendmentor project, and when you complete a project and submit it , it automatically takes a screenshot. But retrieving the JSON appearantly takes too long , as the screenshot is just before retrieval . So it doesn’t look right.

Here’s the github
github

in displayData() I have:

         let array= '';
	data.forEach((element,index) => {
		//empty alt for aria as are decorative img
	    array+=(`<p><img class='icon' alt='' src=${element.icon}> ${element.category}  <span class='right-dark-font${index}'>${element.score}<span class='inherit-position light-font'>/100</span></span></p>`);
    });
    

then right below this code I tried

replaceHtml('.results', array)

as well as

results.innerHTML = array.join(' ');

and I tried

$('.results').append(array);

None seem to speed it up enough so the screenshot works.
I got the replaceHTML() function from here

https://blog.stevenlevithan.com/archives/faster-than-innerhtml

I also read a stackoverflow post here that give some hints:

https://stackoverflow.com/questions/18393981/append-vs-html-vs-innerhtml-performance

As none of these seem to do it , I’m at a loss.
Hope someone can give some insight.

I thought about using D3 as I used JSON retrieval in another frontendmentor project that I solved with D3 and JSON data retrieval, and that screenshot worked out fine, but it just seem overkill, and especially as the bars length aren’t dependent on the data values.

Thanks

I had forgotten I used a string for append and resultsHTML and array for innerhtml.
like so:

let array= []; let string='';
	data.forEach((element,index) => {
	    string+=`<p><img class='icon' alt='' src=${element.icon}> ${element.category}  <span class='right-dark-font${index}'>${element.score}<span class='inherit-position light-font'>/100</span></span></p>`;
    });
	//replaceHtml('.results', string)
	//results.innerHTML = array.join(' ');
	$('.results').append(string);

I’ve tried either of these only off course, but it still is to slow .
Any tips?

Did you try it without corsproxy/jsonkeeper as we suggested in your old thread?

I see no reason why you have to use that. Just put the data in a file and import it. It’s not like you are using an actual API.

I doubt the slowdown is caused by the DOM manipulation.

1 Like

I just wanted to practice using fetch() etc, but I will try what you suggested tomorrow.
Thanks

I actually tried it now, couldn’t sleep.
I followed this tutorial, like I did last time I had trouble with this (you have great memory)

freecodecamp tutorial

But , like last time , I get a CORS proxy error.

 //I added type='module' to the script tag in my index.html file
<script  type='module'  src='results-summary-component-main.js'></script>
 //and I added this statement to the top of my js file
import data from 'data.json' assert { type: 'json' };

The data.json file is in my github project with the other source files. I removed the above two statements as it wouldn’t work at all just gives the CORS error

I know you said I need to host it remotely or local? I was hoping that this would work as it seems easiest for such a small project.

Do you know of any easy to use hosting sites , preferably that I don’t need to create an account for.
Thanks

I have never submitted a frontendmentor project but I would assume it has to be hosted somewhere. How else can it take a screenshot of the live site?

I would suggest Netlify as an easy-to-use option for hosting.


You do not need to use import assert. It isn’t supported in all browsers yet anyway.

You can put the data inside a someName.json file and fetch it as if it was a remote resource.

fetch("./data.json")
  .then((response) => response.json())
  .then((data) => {
    console.log(data);
  });

data.json

[
  {
    "category": "Reaction",
    "score": 80,
    "icon": "./assets/images/icon-reaction.svg"
  },
  {
    "category": "Memory",
    "score": 92,
    "icon": "./assets/images/icon-memory.svg"
  },
  {
    "category": "Verbal",
    "score": 61,
    "icon": "./assets/images/icon-verbal.svg"
  },
  {
    "category": "Visual",
    "score": 72,
    "icon": "./assets/images/icon-visual.svg"
  }
]

Or you can put the data in a js file someName.js and import it.

import { data } from "./data.js";
console.log(data);

data.js

export const data = [
  {
    category: "Reaction",
    score: 80,
    icon: "./assets/images/icon-reaction.svg",
  },
  {
    category: "Memory",
    score: 92,
    icon: "./assets/images/icon-memory.svg",
  },
  {
    category: "Verbal",
    score: 61,
    icon: "./assets/images/icon-verbal.svg",
  },
  {
    category: "Visual",
    score: 72,
    icon: "./assets/images/icon-visual.svg",
  },
];

1 Like

Thanks. I tried hosting both a json and js data file here: https://www.file.io/

When using the data. js file

// added to index.html above other js script tag
<script type="module" src="https://file.io/CFTJnN9CnQv1"></script>

and in my js file I added this line at the top

import { data } from "https://file.io/CFTJnN9CnQv1";

This did not work, I got all these errors

Uncaught SyntaxError: Cannot use import statement outside a module (at results-summary-component-main.js:3:1)
index.html:1 Access to script at ‘https://www.file.io/3Xh9/download/CFTJnN9CnQv1’ (redirected from ‘Deleted’) from origin ‘null’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
index.html:47 GET https://www.file.io/3Xh9/download/CFTJnN9CnQv1 net::ERR_FAILED 200

Then I tried with the data.json and feth method

function getJson() {
    return fetch('https://file.io/CFTJnN9CnQv1')
     .then(response => response.json())
     .then(response => {return response;})
     .catch(err => {
       console.error(err);
     });  
}

async function displayData(){
	const results= document.querySelector('.results');
	const data= await(getJson());
	let array= []; let string='';
	data.forEach((element,index) => {
		//empty alt for aria as are decorative img
	    string+=`<p><img class='icon' alt='' src=${element.icon}> ${element.category}  <span class='right-dark-font${index}'>${element.score}<span class='inherit-position light-font'>/100</span></span></p>`;
    });
	//replaceHtml('.results', string)
	//results.innerHTML = array.join(' ');
	$('.results').append(string);
}

and got even more errors:

results-summary-component-main.js:32 GET https://www.file.io/bkZw/download/CFTJnN9CnQv1 net::ERR_FAILED 200
getJson @ results-summary-component-main.js:32
displayData @ results-summary-component-main.js:42
(anonymous) @ results-summary-component-main.js:67
dispatch @ jquery.min.js:2
y.handle @ jquery.min.js:2
load (async)
add @ jquery.min.js:2
(anonymous) @ jquery.min.js:2
each @ jquery.min.js:2
each @ jquery.min.js:2
Se @ jquery.min.js:2
on @ jquery.min.js:2
(anonymous) @ results-summary-component-main.js:65
results-summary-component-main.js:36 TypeError: Failed to fetch
at getJson (results-summary-component-main.js:32:12)
at displayData (results-summary-component-main.js:42:20)
at results-summary-component-main.js:67:2
at dispatch (jquery.min.js:2:43336)
at y.handle (jquery.min.js:2:41320)
(anonymous) @ results-summary-component-main.js:36
Promise.catch (async)
getJson @ results-summary-component-main.js:35
displayData @ results-summary-component-main.js:42
(anonymous) @ results-summary-component-main.js:67
dispatch @ jquery.min.js:2
y.handle @ jquery.min.js:2
load (async)
add @ jquery.min.js:2
(anonymous) @ jquery.min.js:2
each @ jquery.min.js:2
each @ jquery.min.js:2
Se @ jquery.min.js:2
on @ jquery.min.js:2
(anonymous) @ results-summary-component-main.js:65
results-summary-component-main.js:44 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading ‘forEach’)
at displayData (results-summary-component-main.js:44:7)

It only works when I used https://corsproxy.io/?https://www.jsonkeeper.com/b/R41L
I’m at a complete loss. I hosted the file, it should work?

Thanks

Thanks. Hosting seems to be the biggest issue.
Lasjorg suggested netify , but that site seems way too cumbersome for something so minor. Any site suggestion that allow to load just a single file and quick and easy to use , with no account ?
Thanks !

Netlify is super simple to use. They even let you use drag and drop.

Besides, now is as good a time as any to start learning to host your sites.


Why are you so determined to have the data live outside your app? It isn’t going to be updated outside the app anyway. It is static fixed data that won’t change. They provide you with a data.json file so you can use it to dynamically populate the UI with the data, but the data is static and won’t change. There is really no point in trying to use it from an external resource.

If it was actual API data that updated over time then it would make sense to have a backend for it (server and DB).

1 Like

I tried that , with just my json file both in github or local in the same file as the source files on my computer and I will get CORS errors ? That’s why I went with trying to host and fetch/import?

So how do I solve this now, as it’s just not making any sense anymore?
any tutorial that would explain this clearly or so maybe?
Thanks

So the options are either to keep the json file local or host it.

I tried with keeping the json file local, saved as a data.js
and followed this tutorial, got the same usual CORS errors

import local js file tutorial

Sadly I’m beginning to believe more and more I’m not cut out for this.
Clearly I’m an idiot.

So what are my options if I want to keep the json file local ?

And if I were to host the json file (cant find where) then I can use fetch / import as I have been using ?

I’m just so lost atm. Sorry for the endless posts, but this is frustrating as it’s all vague and many tutorials assume I’m using node.js or am able to host a json file.

Thanks

Sorry I’m confused Lasjorg said I should just keep the json file local as it’s static ?
I already had a working version, just too slow.

And how can I host just a JON file somewhere besides in my github repo?

I have tried with the json file within my github repo
I tried this with fetch and import both didn’t work (CORS error), I could only get fetch to work using both corsproxy and jsonkeeper (the data is stored in jsonkeeper instead not github repo)
fetch(‘https://corsproxy.io/?https://www.jsonkeeper.com/b/R41L’)

but that is too slow.

https://github.com/cmb347827/results-summary-component-main/blob/main/results-summary-component-main.js

I don’t understand how to do with my json file in my github repo other than what I already have? It works but just too slow.

Thanks

I replied, but not to you I see now. Just wanted to make sure you’d see.
Thanks :slight_smile:

Ok it works with a github.raw link. I think I tried that before with another project and it didn’t work then , so I hadn’t thought about it anymore to try again.

The screenshot works correctly now

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.