1

I'm looking for the proper way to load strings into Javascript code.

For example if I have about 300 strings like this one:

 '<h1>Some text</h1>' 

I want to load from some external source with loading of page.php into JS script.

I want avoid listing of strings as variables var v1 = '<h1>Some text</h1>'; or in list var lst = ["<h1>Some text</h1>", "<h1>Some text2</h1>"]; included to .js, but load strings to array from outside.

One way is using of MySQL database given the fact that static sequence is important to use ID for assigning string values to special variables.

But I'm not sure if connection with database is a best, fast and soft way for this particular case, when list is not too big, requires static sequence, not dynamically updated and must be outside of .js document and loaded in to array with page load.

I don’t see the point of loading from one .js to another .js, if my goal is remove listing from .js. Мaybe I can use .xml, or something else, more suitable what is possible.

lf80
  • 455
  • 3
  • 10
  • 22

1 Answers1

1

You could do so by putting those strings into a Json file

Your Json file (myData.json):

{
 "textOne": "Some text",
 "textTwo": "Some text",
 "textThree": "Some text",
}

Your Javascript:

const messages= require('./myData.json');


const messageOne = messages.textOne;
Ivanhoe Cheung
  • 80
  • 2
  • 10
  • just to make it clear, I've added `myData.json` in same directory with `myJs.js`, is that correct? Because `const messages = require('./myData.json');` throws `Uncaught ReferenceError: require is not defined`. So, if `require()` is not a feature that is built into the browser, then what should I use in this case – lf80 Sep 06 '19 at 04:19
  • you will need NodeJs to use require. If you want to import json without NodeJs, you could use import . You may refer this: https://stackoverflow.com/questions/34944099/how-to-import-a-json-file-in-ecmascript-6 – Ivanhoe Cheung Sep 06 '19 at 04:43