Javascript src text file

How can I get the content of the file specified as the ‘src’ of a tag?

I would like to get the content of the «script.js» file. I’m thinking about something like document.getElementById(«myscript»).text but it doesn’t work in this case.

I’m having hard time figuring out why you need to access the content? Can you give some information about what you plan to do with it?

Where would you cache it? I mean, how would you get your cached data to persist beyond the lifetime of the script as loaded in the page?

Markus: I recommend adding a clarification to your quiestion or you’ll just keep getting answers in the same vein as those below 🙂

By invoking a javascript function which stores this value for me. But that is not really in the scope of this question.

This question is a few years old. However, I’d just like to drop in my 2 cents regarding the modern use of this. There is an increasing trend in the use of client-side templates, and generally the way to define templates outside of javascript is to embed the templates within a

17 Answers 17

tl;dr script tags are not subject to CORS and same-origin-policy and therefore javascript/DOM cannot offer access to the text content of the resource loaded via a tag, or it would break same-origin-policy .

long version: Most of the other answers (and the accepted answer) indicate correctly that the «correct» way to get the text content of a javascript file inserted via a loaded into the page, is using an XMLHttpRequest to perform another seperate additional request for the resource indicated in the scripts src property, something which the short javascript code below will demonstrate. I however found that the other answers did not address the point why to get the javascript files text content, which is that allowing to access content of the file included via the would break the CORS policies, e.g. modern browsers prevent the XHR of resources that do not provide the Access-Control-Allow-Origin header, hence browsers do not allow any other way than those subject to CORS , to get the content.

With the following code (as mentioned in the other questions «use XHR/AJAX») it is possible to do another request for all not inline script tags in the document.

function printScriptTextContent(script) < var xhr = new XMLHttpRequest(); xhr.open("GET",script.src) xhr.onreadystatechange = function () < if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) < console.log("the script text content is",xhr.responseText); >>; xhr.send(); > Array.prototype.slice.call(document.querySelectorAll("script[src]")).forEach(printScriptTextContent); 

and so I will not repeat that, but instead would like to add via this answer upon the aspect why itthat

Читайте также:  Дневник начинающего верстальщика

Источник

How to access plain text content retrieved via in JavaScript?

When using , 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.

I would guess that the browsers don’t bother keeping the content (except perhaps in the browser’s cache for a while). Once the script has been evaluated, the source isn’t needed any more so it would just be wasting memory.

Interestingly, Chromium doesn’t even bother to download external script resources with type attribute being any MIME type not to be interpreted as script as listed here [w3.org/TR/html5/the-script-element.html#scriptingLanguages] then I wonder why do all this [w3.org/TR/html5/…

4 Answers 4

First of all, the text attribute of the HTMLScriptElement is the preferred method to access the text of an inline 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 the script element (ignoring any other nodes such as comments or elements), in tree order. On setting, it must act the same way as the textContent IDL attribute.

Since the 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.

    

Источник

Use JS variable to set the src attribute for tag

None of these ways were successful. Any suggestions on what is going wrong?

There is a popular script loading utility called require.js. It optimizes script loading and dependencies by making synchronous calls asynchronous. This may be of interest.

Читайте также:  Php mysql date select date format

If you got an answer, you should accept one of the solutions. 🙂 or provide the answer you found useful.

5 Answers 5

Though CDATA works fine, using document.createElement is also a great choice.. Especially if you intend to append some value to a URL, say for cache busting..

var JSLink = "/Folder/sub_folder/version.js?version mt24">
)" data-controller="se-share-sheet" data-se-share-sheet-title="Share a link to this answer" data-se-share-sheet-subtitle="" data-se-share-sheet-post-type="answer" data-se-share-sheet-social="facebook twitter devto" data-se-share-sheet-location="2" data-se-share-sheet-license-url="https%3a%2f%2fcreativecommons.org%2flicenses%2fby-sa%2f3.0%2f" data-se-share-sheet-license-name="CC BY-SA 3.0" data-s-popover-placement="bottom-start">Share
)" title="">Improve this answer
)">edited Apr 21, 2014 at 7:07
answered Mar 1, 2013 at 12:43
3
    how bout if I need to load multiple js files. is there a specific syntax, or do I have to loop this whole script ?? thanks !!
    – ChickenWing24
    Jun 22, 2015 at 3:17
    Loop the whole script.. Any code you write would basically do that. Sorry for late response.
    – Mahesh
    Dec 3, 2015 at 14:57
    I tried this, and it works, but not as expected. In my case the sourced script is just a long text variable, a list of photos, etc., but when called upon in a resident script that variable is empty. unless. I insert an 'alert" statement in there. It seems some event must be triggered before the variable gets the string. Any ideas? I posted the problem here (stackoverflow.com/questions/54583628/…) but all responses were about off-topic issues.
    – M610
    Feb 13, 2019 at 20:07
Add a comment|
7

I use something similar to choice two. There is a slight mistake in your code because "google.com" needs to be surrounded by quotes.

To improve compatibility, you might want to write it as:

document.write("");

In this situation, x would be the file to be included. You can define it as:

var x = "http://google.com/script.js"; 

Источник

Include .txt file in existing javascript function [duplicate]

I have this javascript function which requires some variables I would like to be called from an external .txt file instead:

  
  

Are you using any kind of server-side technology? If so, this becomes easier. If not, you can use a client-side build process that would turn your text file into whatever JavaScript you needed. We need more details.

I would prefer doing this client-side. The txt file shouldn't be turned into a javascript but rather be included inside the said function.

Show a practical example of your case. What you need to store in the text file and what you're going to with it.

1 Answer 1

Option 1: load txt into variable

you can load a .txt file synchronously via javascript/ajax. have in mind that your javascript code execution will wait at this point until the file is loaded.

var request = new XMLHttpRequest(); request.open('GET', 'text.txt', false); request.send(); var textfileContent = request.responseText; 

you can also do this asynchronously. although in this case your program logic will have to wait for the file to be loaded:

var request = new XMLHttpRequest(); request.open('GET', 'text.txt'); request.onreadystatechange = function() < if (request.readyState === 4) < var textfileContent = request.responseText; // continue your program flow here >> request.send(); 

execute javascript from variable (discouraged)

it is also possible to have javascript code evaluated out of a string. although this method is discouraged:

Option 2: include javascript through script

if it is javascript that you want to load, another solution is to add a script tag to the dom:

var script = document.createElement('script'); script.type = 'text/javascript'; script.src = "text.txt"; document.body.appendChild(script); 

Option 3: use json to initialize variables (best for your needs)

if you are just loading variable values json might make more sense to you. create a textfile like this:

[ ["1070","08/21/2014 15:32 +0300"], ["1071","08/21/2014 16:00 +0300"], ["1072","08/21/2014 16:00 +0300"] ] 

read about the json syntax here

than load the json file like this:

var request = new XMLHttpRequest(); request.open("GET", "json.txt", false); request.send(null); var data = JSON.parse(request.responseText); 

your data is now in an array. you might want to access the values in a loop:

Option 4: merge before runtime

if you have a preprocessor setup you might want to use it to put the files together. alternatively the unix command line tool cat can easily merge two files:

cat file1.txt file2.txt > new.txt 

Источник

How to get the location (src) of a javascript file?

How can the code in howdy.js know about http://mysite.com/scripts/howdy.js ? Edit: Clarification. I cannot rely on searching the DOM for my script tag because I need to know about it before the DOM may be ready.

@tenfour - There are other scripts that howdy.js may pull in from the same directory and I can't be certain where howdy.js will be hosted (test, prod, qa, client host, etc). It's not awesome but it is a business requirement. @Marcel - Yes, you are right, It is a dup. But I'll leave it up as I couldn't find that answer with the search terms I used.

4 Answers 4

In the moment in which the current script is being executed, will be the last script element in the DOM, therefore you can get it by:

var scripts = document.getElementsByTagName('script'), currentScriptSrc = scripts[scripts.length-1].src; 

Check this example that loads this script.

Edit: Taking in consideration the @kangax's comment, about the async and defer attributes, the only safe way IMO, previously knowing the file name, would be to inspect the script elements on the page, examining its src attribute, some libraries like Scriptaculous.us use this technique, for example:

var scripts = document.getElementsByTagName('script'), len = scripts.length, re = /howdy\.js$/, src, howdyScriptSrc; while (len--) < src = scripts[len].src; if (src && src.match(re)) < howdyScriptSrc = src; break; >> ​ 

Источник

Оцените статью