Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include text file into javascript

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

I was thinking to use another element to hold the text inside some comments, but I don't know how to read it's source code with javascript.

Something like:

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

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

In myfile.js: /* some text */

like image 207
mihai Avatar asked Sep 15 '11 15:09

mihai


1 Answers

You can put anything you want into a script tag if you give it a "type" that's not something the browser understands as meaning "JavaScript":

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

You can get the contents via the "innerHTML" property:

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

Here is a jsfiddle to demonstrate.

That trick is popular lately with people doing client-side page building via templates.

like image 160
Pointy Avatar answered Nov 08 '22 04:11

Pointy