How to link to text file in HTML for script use - javascript

What I'm after is this idea: The document contains some link to a text file (for load order reasons, I have several excessively bulky script and image files as well as a huge wall of HTML and want to get this operation done within 5 seconds even on 5kb/s) and then a script is able to reference this text file (to avoid messy code), a bit like:
textFile = document.getElementById ("textFileLink");
someText = textFile.read ();
doSomething (someText);
Some ideas I have tried:
Use the link toString method mentioned in passing in the living standard, this merely returns the url itself.
Instead have a script which exists solely to dump a 10k character string into a global variable (definitely bad)
As above but into a display:none HTML element (maybe not quite as bad?)
As above but LocalStorage?
is this possible, or do I have to do some kind of server-side black magic?

Try using the fetch API:
fetch('path/to/demo.txt').then((res) => res.text()).then((data) => {
// code
});
Fetch should be relatively quick... tell me if it works or if there are errors

Related

Duplicate an HTML file (and its content) with a different name in Javascript

I have an HTML file with some Javascript and css applied on.
I would like to duplicate that file, make like file1.html, file2.html, file3.html,...
All of that using Javascript, Jquery or something like that !
The idea is to create a different page (from that kind of template) that will be printed afterwards with different data in it (from a XML file).
I hope it is possible !
Feel free to ask more precision if you want !
Thank you all by advance
Note: I do not want to copy the content only but the entire file.
Edit: I Know I should use server-side language, I just don't have the option ):
There are a couple ways you could go about implementing something similar to what you are describing. Which implementation you should use would depend on exactly what your goals are.
First of all, I would recommend some sort of template system such as VueJS, AngularJS or React. However, given that you say you don't have the option of using a server side language, I suspect you won't have the option to implement one of these systems.
My next suggestion, would be to build your own 'templating system'. A simple implementation that may suit your needs could be something mirroring the following:
In your primary file (root file) which you want to route or copy the other files through to, you could use JS to include the correct HTML files. For example, you could have JS conditionally load a file depending on certain circumstances by putting something like the following after a conditional statement:
Note that while doing this could optimize your server's data usage (as it would only serve required files and not everything all the time), it would also probably increase loading times. Your site would need to wait for the additional HTTP request to come through and for whatever requested content to load & render on the client. While this sounds very slow it has the potential of not being that bad if you don't have too many discrete requests, and none of your code is unusually large or computationally expensive.
If using vanilla JS, the following snippet will illustrate the above:
In a script that comes loaded with your routing file:
function read(text) {
var xhr=new XMLHttpRequest;
xhr.open('GET',text);
xhr.onload=show;
xhr.send();
}
function show() {
var text = this.response;
document.body.innerHTML = text;//you can replace document.body with whatever element you want to wrap your imported HTML
}
read(path/to/file/on/server);
Note a couple of things about the above code. If you are testing on your computer (ie opening your html file on a browser, with a path like file://__) without a local server, you will get some sort of cross origin request error when trying to make an XML request. To bypass this error, either test your code on an actual server (not ideal constantly pushing code, I know) or, preferably, set up a local testing server. If this is something you would want to explore, its not that difficult to do, let me know and I'd be happy to walk you through the process.
Alternately, you could implement the above loading system with jQuery and the .load() function. http://api.jquery.com/load/
If none of the above solutions work for you, let me know more specifically what it is that you need, and I'll be happy to give a more useful/ relevant answer!

How to modify HTML from another file with JavaScript/jQuery

I need a reference of a HTML element that has an id of #searchResults
$.get('search-for-prospect', function() {
_content.find('.prospect-container').sort(function(a,b){
...stuff...
}).appendTo('#searchResults');
})
I tried using jQuery's get to get the that element, but it doesn't work as expected.
I need to get a reference of searchResults and append to it. How can I achieve that?
The only way to get HTML from another page with javascript is by making AJAX call (in fact js template engines work this way).
So you have to $.ajax the page you want, parse it as HTML and do what you want to do.
Beware: you are not editing the HTML file itself, but just its "in memory copy".
Javascript, as far as it is used as client-side technology, does not allow modifying files or in general accessing the file system. So if you're looking for some trick to write in the HTML, you're on the wrong way

How to access one JS file from a function inside a JS file

So, I am making a "ModReady" version of my JavaScript game where you can easily mod a game. The point is to click a button inside a ModReady version of a game, type the filepath of the mod you want to run, and the JavaScript executes it.
I have a problem though. I don't think you can run a separate .js file from inside a function.
Is this possible to do?
Depends on where the game is relative to the mod authors file. The short answer is yes, but you have to be a little cunning if the mods script doesn't exist in the same place as yours.
The safest and easiest method would be to offer a version of the code base which others can download and mod themselves.
Alternatively theres several methods of running code cross browser, i wouldn't advise letting other peoples code reside on your server.
The simplest method would be similar to the way code pen or JSfiddle work, you have a text box which the mod adds the code to. Then either run your game in an iframe with the text box contents included in a script element, or store the string in a HTML 5 local storage element, load the game page querying the local storage and add the local storage string to a new script element.

How do I get the path of the currently running script with Javascript?

We have an IE extension implemented as a Browser Helper Object (BHO). We have a utility function written in C++ that we add to the window object of the page so that other scripts in the page can use it to load local script files dynamically. In order to resolve relative paths to these local script files, however, we need to determine the path of the JavaScript file that calls our function:
myfunc() written in C++ and exposed to the page's JavaScript
file:///path/to/some/javascript.js
(additional stack frames)
From the top frame I want to get the information that the script calling myfunc() is located in file:///path/to/some/javascript.js.
I first expected that we could simply use the IActiveScriptDebug interface to get a stacktrace from our utility function. However, it appears to be impossible to get the IActiveScript interface from an IWebBrowser2 interface or associated document (see Full callstack for multiple frames JS on IE8).
The only thing I can think of is to register our own script debugger implementation and have myfunc() break into the debugger. However, I'm skeptical that this will work without prompting the user about whether they want to break into the debugger.
Before doing more thorough tests of this approach, I wanted to check whether anyone has definitive information about whether this is likely to work and/or can suggest an alternative approach that will enable a function written in C++ to get a stack trace from the scripting engine that invoked it.
Each script you load may have an id and each method of the script calling myfunc() may pass this id to myfunc(). This means that first you have to modify myfunct() and finally alter your scripts and calls.
This answer describes how I solved the actual issue I described in the original question. The question description isn't great since I was making assumptions about how to solve the problem that actually turned out to be unfounded. What I was really trying to do is determine the path of the currently running script. I've changed the title of the question to more accurately reflect this.
This is actually fairly easy to achieve since scripts are executed in an HTML document as they are loaded. So if I am currently executing some JavaScript that is loaded by a script tag, that script tag will always be the last script tag in the document (since the rest of the document hasn't loaded yet). To solve this problem, it is therefore enough just to get the URL of the src attribute of the last script tag and resolve any relative paths based on that.
Of course this doesn't work for script embedded directly in the HTML page, but that is bad practice anyway (IMO) so this doesn't seem like a very important limitation.

Cache HTML Content by storing inside javascript variable in external js file?

I have a web application where the masterPage/template contains some static HTML that never changes but is sent with every request. (a lot of this HTML are hidden elements that are shown after a user does something)
I'm wondering if there is some way of caching it?
I was considering putting the HTML inside a javascript variable and doing a document.write or a jquery $(tag).html(cachedHTML); to get that content. The benefit here is that the javascript file will be cached by the browser and that HTML won't be passed along (speeding up pageload and decreasing bandwith).
Is there a more elegant solution? And if I do go this route, is there an easy way to convert all the HTML to be inside a javascript string without going through the HTML and formatting it? (remove spaces, escape double quotes, etc...) Thoughts?
Thanks!
Update: Here is the YSlow info... does this page seem too large? (There are 3597 DOM elements)
Some notes: In terms of the JS files, there are three main ones jquery, jquery-ui, and my global minified js, the rest are generated by asp.net or things like getsatisfaction
I may be wrong, but to me, it sounds well-intentioned but unnecessary. If your server is configured correctly, the HTML output will be gzipped. If we're not talking about megabytes of HTML, every image on your page will take more bandwidth than the document's markup.
In my experience, the greater worry about really huge chunks of HTML data is how the browser handles it. A 2-3 MB HTML document will take up the hundredfold of memory when finally rendered. If that's the case in your scenario, you may have a design problem at hand that even caching wouldn't solve.

Categories

Resources