How to include text file into javascript

别来无恙 提交于 2020-01-01 09:16:13

问题


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 */


回答1:


Without using ajax or any server code... sorry mate but you can't :(




回答2:


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.




回答3:


Building on Pointy's answer, to import from local files do this:

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

You could also use this to target an external file:

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


来源:https://stackoverflow.com/questions/7433250/how-to-include-text-file-into-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!