is this possible?
<html>
<script src="local.js>
<script>
// get contents of local.js file here without doing an ajax call?
</script>
</html>
local.js resides on the same server, and I know that by doing an xhr call I can get its contents (if not on file://).
But, as it is already requested synchronously by the browser, its contents is known to the document so I hope there is a way to access it? The document.scripts collection was no help to me.
Somewhat like getting innerHTML (which works for scripts defined in-page)?
I'm not sure on how to get the included javascript code, nor why you would need this, but how about going the other direction?
Instead of having a script tag, make a XHR call to the file and eval its contents + keep its contents as a variable also.
**Disclaimer: I cannot see why you would need this, nor would I actually suggest you use this method, but it's a work-around.
Are you assuming XHR will not use the cached version? It will, there may be a request, but it should be fast (reuse the same HTTP connection) and return 304 (not modified). So the cached version will be used unless your JavaScript file's HTTP response headers prohibit or do not specify caching directives (but usually they should).
I suspect that while the contents of the script are known to the browser, they're not known to the document, and are therefore not accessible via the DOM API. So you will have to use the XHR approach. With a bit of luck, if you ensure the script is properly cached, the XHR request will pull the script contents from the local cache anyway.
Related
I've created a script which autoloads javascript files based on the users location. Like any other loaders, I create a <script> element, set it's src attribute and add it to <head>. I then listen for onload and onreadystatechanged etc. events, then check for the presence of a value exposed by the file. This works.
The problem is, when supplied with an invalid cross origin url "http://fail_on_purpose", my ISP returns HTML (directing the browser to reload with a different address). I can catch this in the onload event, but it's too late. The HTML has already been injected on the page within the <script> tags. This then causes the browser (firefox at least) to issue a SyntaxError exception.
All I can do is remove the offending element from the DOM. But, I don't know if this is going to cause problems in other browsers, so I would prefer to not have the error at all.
What is the best way to check for a valid javascript file then inject it into the page?
Update:
Issuing a HEAD or GET request to check if the file exists/is valid, doesn't work due to the "Cross Origin" protection in the browser. I don't have access to the CDN, so that is an unfixable problem.
You could send a HEAD request and parse response headers to see if the page returns successfully, i.e. not with redirection, client error or server error response code. Any decently implemented server should set correct response code.
Ideally, you'd also check content-type to include application/javascript, if the server is set up to set it correctly.
If this matches, you know that the script exists, so you can then proceed with loading it the same as you do now.
Alternatively, you already get these headers with GET request, so you could do all that with a single request. But with incorrect request, you'll be waiting for all the payload before determining it's incorrect, which will take up more time and waste data transfer. The latter is something worth considering if you're expecting mobile users, you wouldn't want to waste data plans like that.
As Sumit suggests, you might load the script via an Ajax request, then check it somehow (e.g. because you know that it contains a particular string).
On success, just proceed as you did - append a <script> tag to the head or body element with the "src" attribute set. If caching is enabled for the URL, the browser won't do another HTTP request for that.
Using the Ajax-loaded JS code directly (by setting scriptElem.text instead of the "src" attribute) is another option, but not as good, since it is subject to CORS restrictions. See jQuery's DOMEval function, https://code.jquery.com/jquery-3.1.0.js (line 77)
Since you want to load the code from the Google servers, the "src"-attribute version is better.
I have a javascript file named myscripts.js in the "scripts" folder of my webserver. It could be accessed with this:
http://www.example.com/scripts/myscripts.js
Within myscripts.js is a javascript function which makes a XMLHttpRequest call to somemethod.html of my website. Here is the calling code:
xmlhttp.open("GET","somemethod.html",false);
99% of the time everything works fine. But I am finding some browsers are prepending "scripts/" to the call. So the result is a call like this:
http://www.example.com/scripts/somemethod.html
when it should be this:
http://www.example.com/somemethod.html
This is a custom built webserver (i.e. I basically handle ALL requests).
Should my webserver be able to handle this? Or is this just some fluky browser that I should not worry about?
Should I not be using "relative" paths in the javascript? And instead use absolute calls in the java script? e.g.: instead of "somemethod.html" it should be coded like this:
xmlhttp.open("GET","http://www.example.com/somemethod.html",false);
It's absolutely fine (and overwhelmingly the standard of practice) to use relative paths in the JavaScript, just be aware of what they're relative to: The document in which you've included the JavaScript (not the JavaScript file.) You seem clear on this, but just emphasizing.
I've never seen a browser get this wrong. It's possible the requests you're seeing are from a poorly-written web crawler looking at the source of the JavaScript rather than doing something intelligent like figuring out where/how it's run.
Just for clarity, though, about the relative thing (more for lurkers than for you):
Given this structure:
foo.html
index.html
js/
script.js
In that structure, if you include script.js in index.html:
<script src="js/script.js"></script>
...then use code in that script file to do an XHR call, the call will be relative to index.html, not script.js, on a correctly-functioning browser.
I never use relative requests, I built my own url handing js code to build up and pass urls around with a 'toString' method to give me exactly the url I need.
Also as an aside, try not to use synchronous XHR calls anymore, ideally you should use async and call backs, it's a pain, but it's for the best.
client . open(method, url [, async = true [, username = null [, password = null]]])
Sets the request method, request URL, and synchronous flag.
Throws a "SyntaxError" exception if either method is not a valid HTTP method or url cannot be parsed.
Throws a "SecurityError" exception if method is a case-insensitive match for `CONNECT`, `TRACE` or `TRACK`.
Throws an "InvalidAccessError" exception if async is false, the JavaScript global environment is a document environment, and either the timeout attribute is not zero, the withCredentials attribute is true, or the responseType attribute is not the empty string.
source: http://xhr.spec.whatwg.org/#the-open%28%29-method
I'm building a local html file to show dynamically some data from an XML file and by using Chrome's Inspector I figured my XML file is not being parsed because it is "not hosted on a webserver"
XMLHttpRequest cannot load data.xml. Cross origin requests are only supported for HTTP.
I know that there are a few flags I could pass to Chrome/web browser to workaround this limitation but I'm looking into some alternative method. I will probably have to distribute this files to a few people and teaching them how to pass flags to the browser is not an option for me. Hosting them on a web server is not an option either.
Thanks a lot in advance.
No ghost unless you set up a local server or host the XML file locally. Ajax has to follow the same origin policy.
If you're willing to use a library you can use jQuery's AJAX method to perform a cross-domain request (i'm not entirely certain that jQuery will support what you're trying to do). JSONP works, but you have XML data...
You could try loading it in a script tag anyway and see if you can get the innerHTML value without breaking the script; once you're done getting the text from it, remove the script from the page. You may be able to get at the data before the browser tries to parse the script by attaching onload and onreadystatechange events to the script element.
var s = document.createElement('script');
s.src = '/path/to/file.xml';
s.onload = s.onreadystatechange = getData;
function getData(e)
{
//get the text out of the script element
//remove the event handler from the script element
//remove the script from the page
}
document.getElementsByTagName('body')[0].appendChild(s);
I didn't test it, but it might work.
How about setting up a local webserver? XAMPP should be easy to install even for novice. Just tell them to put your files in the htdocs folder, run xampp and start the apache server.
Unless there's a compelling reason to have a separate html and xml file, you could just put the data directly in the html file.
I'm afraid if chrome only provides options that you don't like to apply, your application and chrome will not come together. Access via iframe & object does'nt work too, load()-method of createDocument is not supported by chrome(if it does I guess you got the same error).
Whatever you try will be a sideway to pass chrome's restrictions, what cannot be good, because I think they have good reasons to setup these restrictions.
Im trying to load some code from an external domian with js. with script tags the browser is (according to firebug) loading the file. This is the code:
$('<script
type="plaintext"src="http://www.google.de"></sc'+'ript>').appendTo('body');
You cann see after loading the content of the file in this case an html document in firebug but is there any way to access this data for example with js?
No, it's not possible. It would be possible if the src were on the same domain, by using XMLHttpRequest instead.
As a side note, type should be text/plain.
No, it is not possible to get type and src work together in a script!
It is what WHATWG has stated about type when set to anything else than Javascript:
Setting the attribute to any other value means that the script is a
data block, which is not processed. None of the script attributes
(except type itself) have any effect on data blocks.
Data block is pretty useless without src - object or Blob is MUCH better. Loading something else than Javascript is not possible to access. Mime-types has no practical meaning for except the multityde of mimes to load .js (and for except Web Extension writers possibly).
Very simple Ajax request taking employee id and returning the user info as HTML dumb.
Request ajax("employee/info?emp_id=3543")
Response id = 3543name = some name
This is just another simple JS trick to populate the UI. However i do not understand how something like below is equally able to execute correctly and dump the HTML code.
<script type="text/javascript" src="employee/info?emp_id=3543" />
When page encounters following code it executes like the ajax request is executed and dumps code into page. Only difference is its no more asynchronous as in case of Ajax.
Questions :
Is this correct approach ? its +ves and -ves.
Which are the correct scenarious to user it?
Is this also means that any HTML tag taking "src" tag can be used like this?
I have used this kind of javascript loading for cross domain scripting. Where it is very useful. Here is an example to show what I mean.
[Keep in mind, that JS does not allow cross domain calls from javascript; due to inbuilt security restrictions]
On domain www.xyz.com there lies a service that give me a list of users which can be accessed from http://xyz.com/users/list?age=20
It returns a json, with a wrapping method like following
JSON:
{username:"user1", age:21}
If I request this json wrapped in a method like as follows:
callMyMethod({username:"user1", age:21})
Then this is a wrapped json which if loads on my page; will try to invoke a method called callMyMethod. This would be allowed in a <script src="source"> kind of declaration but would not be allowed otherwise.
So what I can do is as follows
<script language="javascript" src="http://xyz.com/users/list?age=20"></script>
<script language="javascript">
function callMyMethod(data)
{
//so something with the passed json as data variable.
}
</script>
This would allow me to stuff with JSON coming from other domain, which I wouldn't have been able to do otherwise. So; you see how I could achieve a cross domain scripting which would have been a tough nut to crack otherwise.
This is just one of the uses.
Other reasons why someone would do that is:
To version their JS files with
releases.
To uncache the js files so that they are loaded on client as soon as some changes happen to js and params being passed to URL will try to fetch the latest JS. This would enable new changes getting reflected on client immediatly.
When you want to generate conditional JS.
The usage you have specified in example wouldn't probably serve much purpose; would probably just delay the loading of page if processing by server takes time and instead a async ajax call would be much preferred.
Is this correct approach ? its +ves
and -ves.
Depends whether you want to use asynchronous (ajax) way or not. Nothing like +ve or -ve.
The later method takes more time though.
Which are the correct scenarious to
user it?
Ajax way is the correct method there in that sense.
Is this also means that any HTML tag
taking "src" tag can be used like
this?
src is used to specify the source path. That is what it is meant to do.