When using <script type="text/plain" src="http://..."></script>
, where the URL refers to a plain text file, is there a way to access the content of the file in JavaScript? The file is transferred to the browser, but the value of innerHTML
property of the script
element is not changed (it remains the empty string). Inspecting the element node in the DOM does not seem to reveal any property through which the content received could be found.
I know that XMLHTTPRequest can be used instead, but I’m interested in the problem why browsers fetch data in the way I described but do not seem to offer any access to it.
First of all, the text
attribute of the HTMLScriptElement
is the preferred method to access the text of an inline <script>
element. DOM-Level-2 and HTML5: 4.11.1 both indicate that a script should have an attribute text
which contains the scripts interior text:
The IDL attribute
text
must return a concatenation of the contents of all the Text nodes that are children of thescript
element (ignoring any other nodes such as comments or elements), in tree order. On setting, it must act the same way as thetextContent
IDL attribute.
Since the <script>
element is empty (you specified an external source), text
, textContent
and innerHTML
are empty. This is because the text
attribute is only set in inline scripts:
If the script is inline and the script block's type is a text-based language:
The value of the
text
IDL attribute at the time the element's "already started" flag was last set is the script source.
So it's not possible to include an external text/plain
using this method.
See also:
<script src="game-engine.js"></script> <!-- game engine isn't inline --> <script type="text/x-game-map"> <!-- but data needs to be inline --> ........U.........e o............A....e .....A.....AAA....e .A..AAA...AAAAA...e </script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With