How to include a text file in javascript

Is there a way to load some text from another file into javascript, without server side code?

I was thinking of using another element to store text inside some comments, but I don't know how to read its source code using javascript.

Sort of:

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

<script> function readMyText() { ... }</script>

In myfile.js: /* some text */

+6
source share
3 answers

Without using ajax or any server code ... sorry, but you cannot :(

+1
source

You can put whatever you want in the script tag if you give it a โ€œtypeโ€ that the browser does not understand as โ€œJavaScriptโ€:

 <script id='Turtle' type='text/poem'> Turtle, turtle, on the ground; Pink and shiny - turn around. </script> 

You can get the content through the "innerHTML" property:

 var poemScript = document.getElementById('Turtle'); var poem = poemScript.innerHTML; 

Here is jsfiddle shown.

This trick has been popular lately with people doing page creation on the client side using templates.

+11
source

Based on Pointy's answer for importing from local files, do the following:

 <script src="foo.txt" id="text" type="text"> </script> 

You can also use this to target an external file:

 <script src="http://foo.txt"></script> 
-1
source

Source: https://habr.com/ru/post/897394/


All Articles