Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading data as .js file vs. loading as JSON

I couldn't find any existing page on this, perhaps I'm not using the right search keywords...

Say I'm implementing a simple JavaScript search engine for my static site, and my searchable contents (a large file) are stored in a file and loaded during initial page load.

Now I can load the content file in two ways:

1. The contents are stored in a Javascript variable in a search_content.js file:

// Large js file
var content = {"pages": [ {"page": "..."}, {...}, ... ]};

In my HTML I load it using:

<script src="search_content.js"></script>

And my search engine would just access the content variable.

2. Keep the searchable content in a JSON file search_content.json:

// Large json file
{"pages": [ {"page": "..."}, { ... } ... ]}

And load the file in my search library after page load:

$.ajax({
  dataType: "json",
  url: url_to_my_json_file,
  data: data,
  success: success
});

Method 1 can be run without a web server, but aside from that, what are the differences, benefits/drawbacks for each method? Are they the same performance-wise?

like image 659
slsdo Avatar asked Feb 12 '15 19:02

slsdo


1 Answers

I would say the latter can be better when there is a noticable delay in the initial rendering of the page, as this can be considered as a way of lazy loading.

Performance-wise the first one would be most likely more efficient, however the perceived performance could be a more important factor here.

One other thing comes to my mind, the second way does not pollute the global scope, this could be an advantage.

like image 159
meskobalazs Avatar answered Oct 27 '22 01:10

meskobalazs