Reload the same javascript file when loading each static page - javascript

I have a few static html pages. All these pages have the following
<script src="my-javascript.js"></script>
I don't want the browser to cache the javascript file, and I want it to get reloaded at page load for each page.
After online search, I found that this trick: adding the following to each page
<script src="my-javascript.js?p=changing_value"></script>
If this is going to work, how can I generate the "changing_value" in a static html page (not PHP, JSP, etc.).
Or some other solutions to force reload the javascript file at each page load for all pages?
Thanks!
UPDATE
I dont have access to server configuration.

After online search, I found that this trick: adding the following to each page
A much better solution is to use caching headers to tell the browser not to cache the file. Configure your server to serve that file with:
Cache-Control: no-cache
Expires: -1
Those are the basic ones, anyway.
If this is going to work, how can I generate the "changing_value" in a static html page (not PHP, JSP, etc.).
If you want to go the query string route, though, just for completeness:
You can get a random value from Math.random(), or as Hemadeus points out, use a timestamp value.
If you need the script load to be blocking (like script tags normally are), this is one of the few remaining use cases for document.write:
<script>
document.write('<script src="my-javascript.js?' + Math.random() + '"><\/script>');
</script>
(Or replace Math.random() with Date.now() to use a timestamp)
If you don't need it to be blocking, then creating the element with createElement is probably cleaner:
<script>
(function() {
var s = document.createElement('script');
s.src = "my-javascript.js?" + Math.random();
document.querySelector("head").appendChild(s);
})();
</script>
Old browsers won't have Date.now. You can get the same value from new Date().getTime().

You could generate the changing_value using a Javascript timestamp.
so you will always have a new version of the js file.

Related

Force browser to reload the Javascript files

I am trying to achieve the below in ASP.NET MVC3 web application which uses razor.
1) In my Index.cshtml file, I have the below reference.
<script src="/MySite/Scripts/Main.js"></script>
2) I load my home page for the first time and a http request is made to fetch this file which returns 200.
3) Then, I made some changes to the Main.js and saved it.
4) Now I just reload the home page (please note that I am not refreshing the page) by going to the address bar and typing the home page url and pressing enter. At this point, I want the browser to fetch the updated Main.js file by making a http request again.
How can I achieve this? I don't want to use System.Web.Optimization bundling way. I knew that we can achieve this by changing the URL (appending version or some random number) everytime the file changes.
But the challenge here is the URL is hardcoded in my Index.cshtml file. Everytime when there is a change in Main.js file, how can I change that hardcoded URL in the Index.cshtml file?
Thanks,
Sathya.
What I was trying to achieve is to invalidate browser cache as soon as my application javascript file (which already got cached in the browser) gets modified at the physical location. I understood that this is simply not achievable as no browsers are providing that support currently. To get around this below are the only two ways:
1)Use MVC bundling
2)Everytime the file is modified, modify the URL by just appending the version or any random number to the URL through querystring. This method is explained in the following URL - force browsers to get latest js and css files in asp.net application
But the disadvantage with the 2nd method is, if there are any external applications referring to your application's javascript file, the browser cache will still not be invalidated without refreshing the external application in browser.
Just add a timestamp as a querystring parameter:
var timestamp = System.DateTime.Now.ToString("yyyyMMddHHmmssfff");
<script src="/MySite/Scripts/Main.js?TimeStamp=#timestamp"></script>
Note: Only update TimeStamp parameter value, when the file is updated/modified.
It's not possible without either using bundling (which internally handles version) or manually appending version. You can create a single file bundle as well if you want.

jquery doesnt cache javascripts which loading from html

Im having a really difficult time here. Actually when I load a HTML file with Jquery which contains Javascript files (included in my html), jquery adds timestamp to the file source to prevent it from being cached whereas this timestamp is not available in our source. What I want to do is remove the timestamp from javascripts to allow them to get cached. It would be great if someone could help me with this.
I have personally used code like the following to set HTML content obtained from an AJAX request, without adding the caching busting query string to any scripts in the HTML.
// Get ajaxHTML from an AJAX request.
var ajaxCache = $.ajaxSetup().cache;
$.ajaxSetup({cache: true});
$('.someelement').html(ajaxHTML);
$.ajaxSetup({cache: ajaxCache});
Basically it changes the default settings temporarily before calling .html, then sets it back afterwards.

Executing a JavaScript file directly from the browser

This sounds like a trivia question but I really need to know.
If you put the URL of an HTML file in the Location bar of your browser, it will render that HTML. That's the whole purpose of a browser.
If you give it a JPG, or a SWF, or even PDF, it will do the right things for those datatypes.
But, if you give it the URL of a JavaScript file, it will display the text of that file. What I want is for that file to be executed directly.
Now, I know that if you use the javascript: protocol, it will execute the text of the URL, but that isn't what I need.
I could have the URL point to an HTML file consisting of a single <script> tag that in turn points to the JavaScript file, but for occult reasons of my own, I cannot do that.
If the file at http://example.com/file.js consists entirely of
alert("it ran");
And I put that URL in the Location bar, I want "it ran" to pop up as an alert.
I'm skeptical that this is possible but I'm hoping-against-hope that there is a header or a MIME type or something like that that I can set and miraculously make this happen.
This is not possible. The browser has no idea what context the JavaScript should run in; for example, what are the properties of window? If you assume it can come up with some random defaults, what about the behavior of document? If someone does document.body.innerHTML = "foo" what should happen?
JavaScript, unlike images or HTML pages, is dependent on a context in which it runs. That context could be a HTML page, or it could be a Node server environment, or it could even be Windows Scripting Host. But if you just navigate to a URL, the browser has no idea what context it should run the script in.
As a workaround, perhaps use about:blank as a host page. Then you can insert the script into the document, giving it the appropriate execution context, by pasting the following in your URL bar:
javascript:(function () { var el = document.createElement("script"); el.src = "PUT_URL_HERE"; document.body.appendChild(el); })();
Or you can use RunJS: https://github.com/Dharmoslap/RunJS
Then you will be able to run .js files just with drag&drop.
Not directly, but you could make a simple server-side script, e.g. in PHP. Instead of
http://example.com/file.js
, navigate to:
http://localhost/execute_script.php?url=http://example.com/file.js
Of course, you could smallen this by using RewriteRule in Apache, and/or adding another entry in your hosts file that redirects to 127.0.0.1.
Note that this is not great in terms of security, but if you use it yourself and know what you're downloading, you should be fine.
<html>
<head>
<script>
<? echo file_get_contents($_GET['url']); ?>
</script>
</head>
<body>
</body>
</html>
In the address bar, you simply write
javascript:/some javascript code here/;void(0);
http://www.javascriptkata.com/2007/05/01/execute-javascript-code-directly-in-your-browser/
Use Node.js.
Download and install node.js and create a http/s server and write down what you want to display in browser.
use localhost::portNumber on server as url to run your file.
refer to node js doc - https://nodejs.org/dist/latest-v7.x/docs/api/http.html
Run - http://localhost:3000
sample code below :
var http = require("http");
var server = http.createServer(function(req,res){
res.writeHead(200,{'Content-Type':'text/html'});
res.end("hello user");
}); server.listen(3000);`
you can write your own browser using qt /webkit and do that.
when user enters a js file in url location you can read that file and execute the javascript .
http://code.google.com/apis/v8/get_started.html is another channel.
not sure if it meets ur need.

Executing custom JavaScript on specific pages of the site from a single file

my js file loads on all pages. Some functions are meant to run only on certain pages like the homepage only http://site.com. Can javascript read the url of the page it's being called from to determine if it's the homepage?
You can use the window.location object to get properties about the location. Some notable properties are:
window.location.href - returns the entire URL of the current page
example: http://www.google.com/subdir/subpage.html
window.location.hostname - returns just the hostname (the domain name, including any subdomains)
example: www.google.com
window.location.pathname - returns just the path (the part following the hostname/domain, but not including the query string (part of the URL that begins with a "?") or the hash (part of the URL that begins with a "#"))
example: /subdir/subpage.html
Although all this works well, I would recommend (like others have mentioned) that it would be better to do this server-side. The server can usually do stuff like this better than the client.
Additionally, if you have all your JS code in a single central file, you could add something like this directly to the page (on the server) to trigger an event for just that page, which may be more reliable than JS location sniffing:
<script type="text/javascript">
// jQuery example
$(document).ready(function () {
// Run function that is specific for this page
MyNamespace.initHome();
});
</script>
Put a unique id attribute on the <body> element for each page, and use that to determine what your JS should do. This is what I do with my single minified file, which (once it concatenates many smaller JS files) looks basically like:
jQuery(function($){
if (!$('body#home').length) return;
//... code specific to the home page
});
jQuery(function($){
if (!$('body#contact').length) return;
//... code specific to the contact page
});
// etc. for each page
But you can just as easily write a more efficient single file as:
jQuery(function($){
if ($('body#home').length){
//... code specific to the home page
}
if ($('body#contact').length){
//... code specific to the contact page
}
});
I think it might be a better idea to figure this out on the server side and call the correct functions/load the correct scripts depending on the page. The server side usually knows better what the current page is for anyways.
You could read the URL as ClosureCowboy said, but that's kind of backwards. Usually, if you know you don't need a JavaScript file, you don't include it on the page.
Keep all of your JS code in a single file, let it load on every page (cached anyways) but here's the catch:
ONLY call the functions you need from the page that needs them
Trying to put "what page am I on" logic in the JS file just seems backwards.
Here is a little piece of code that I have used to set a unique cookie for each page. It should work just fine to get exactly what you want. You can run it through a switch to produce different actions for different pages, or just use a simple if statement to run code only on the home page.
var sPath = window.location.pathname;
var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
console.log(sPath);
I added the console.log so that you can see what it calls the page in the Firebug Console. Change it to alert if you would rather it pop up.
Your JavaScript can get the current URL using window.location.
alert(window.location);

In Javascript any way to know what host script was loaded from?

In javascript, as a script loaded from somer host, is there any way to know what server/host I was loaded from? I need to make additional ajax requests back to that host and would prefer to figure out the host dynamically.
So if you include a javascript file on a page
<script src="http://somehost.com/js/test.js"></script>
when that javascript execute, within test.js ...
var host_loaded_from = ??? // should be somehost.com
Thanks
is there any way to know what server/host I was loaded from?
Yes, it's possible except when the script is loaded asynchronously using defer or async attributes since the last script in the DOM may not necessarily be the currently executing script in that case. See the comments by #kangax for more information.
Also, this same question was posted recently.
Inside your test.js, get the last script element which will be the currently being parsed script (test.js in your case), and get its src.
// test.js
var scripts = document.getElementsByTagName('script');
var src = scripts[scripts.length - 1].src;
One the src is found, parsed the host using regex.
src.match(new RegExp('https?://[^/]*'))
["http://somehost.com"] // for your example
Does the script know its own file name? ("test.js" in the OP question.)
If so, your script could query the dom for all script tags, looking for the ones with a src attribute. But you'd need to watch out for two scripts with the same file name loaded from different servers. Eg
<script src="http://somehost.com/js/test.js"></script>
<script src="http://somehost_number2.com/js/test.js"></script>
Here's JS that looks for all of the script tags in an el:
var scripts = el.getElementsByTagName('SCRIPT');
Nope, sorry.
If the <script> had an id, then maybe. But you can't really rely on that.
Not sure if that can be done with JavaScript. If the script is inside a PHP file do it like this:
...
var host_loaded_from = <?php echo $_SERVER[SERVER_NAME] ?>
...
On my site I include my JS scripts using PHP just for that reason. I'm interested to see if there's a better way.
Due to Same Origin Policy, you can make AJAX requests only to the origin (host + protocol + port), the HTML page (document) was loaded from - which is not necessarily the same as the origin your js was loaded from.
You can use window.location.hostname or document.location.hostname to find out the hostname of the document.

Categories