JavaScript and CSS dynamic versioning - javascript

I had a question regarding dynamic versioning of JavaScript and CSS file references in HTML files. For example:
script src = "test.js?v=1234"
And similarly with CSS references. I have done this in the past using ASP.NET, where I can call a function from the server side to generate a random number everytime the page loads ex:
"test.js?v=<%= myrandomfunc() %>"
I basically don't want the browser to get a cached copy of the css or js reference. I wanted to know if I can do this in JavaScript or jquery without using a server side language like asp or php etc.
Any help is much appreciated.
Thanks !

This is called file revving and it depends on what build system you're using. For Grunt, there's grunt-filerev, for Gulp, there's gulp-rev and gulp-filerev-replace.
If you don't yet use a build system, you might also want to check out Yeoman which will generate just about everything you need, including file revving.

I wanted to know if I can do this in JavaScript or jquery without
using a server side language like asp or php etc.
Yes.
var script = document.createElement('script');
script.onload = function() {
//do your stuff here
};
script.src = "http://whatever.com/the/script.js?v="+(+new Date());
document.getElementsByTagName('head')[0].appendChild(script);
Another option is to send the right headers :

Related

How to read javascript file in frontend javascript/browser

Please read carefully before marking as dupe.
I want to read a javascript file on frontend. The javascript file is obviously being used as a script on the webpage. I want to read that javascript file as text, and verify if correct version of it is being loaded in the browser. From different chunks of text in the js file, I can identify what version is actually being used in the end user's browser. The js file is main.js which is generated by angular build.
I know we can do something like creating a global variable for version or some mature version management. But currently, on production site, that will mean a new release, which is couple of months from now. Only option I have right now is html/js page, which can be directly served from production site, without waiting for new release.
So my question is, is it possible we can read a javascript file as text in hmtl/js code in the browser.
an idea can be :
use fetch api to get a container that can be use to async load the script
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
use text() method which return a promise to get text content
fetch('http://localhost:8100/scripts.js').then((res) => res.text()).then(scriptContent => {
// scriptContent contain the content of your script
// if (scriptContent.includes('version : 1.1.1')
console.log(scriptContent);
});
this is absolutely not an efficient way, but since you want to work without any new version release or working with a version management system
here is the thing
assume file's checksum (md5 sha125 or anything) of V1.0 equals X and you will calculate before the coding part.
if checksum(X) != X{
location.reload()
}
would help for a security features too since it's an important project.
another way of controlling this situation is changing the main.js file's name if it is possible.

List files in website directory without index.html

If a directory on a webserver doesn't have any html files (e.g. index.html), then when you navigate to that url, typically you just see a list of the files in that directory (unless .htaccess was changed to prevent this). Is it possible to get a list of these files in javascript?
you can do it with a get_files function
var files;
function getFilesInFolder(folderServerRelativeUrl) {
var context = SP.ClientContext.get_current();
var web = context.get_web();
var folder = web.getFolderByServerRelativeUrl(folderServerRelativeUrl);
files = folder.get_files();
context.load(files);
context.executeQueryAsync(Function.createDelegate(this, this.OnSuccess), Function.createDelegate(this, this.OnFailure));
}
Any time you write code to display something on the web, you are using a server-side language. HTML is a server-side language, but has extremely limited programming capabilities - can't read the server file system, cannot loop, etc.
So, to do what you are asking you need a server-side language. Either PHP or node.js or Python etc. Almost all webhosts already include PHP, but you can now find some (a2, webhostpython) with the other two. There are TONS of tutorials online for doing what you want with PHP. Tons.
So, to be clear, if you want to code your server-side in javascript, you need to have node.js installed on that server. To use PHP, it's almost certainly already there.
PHP files are identical to HTML files, except they end in .php instead of .html, which allows them to process PHP code between the <?php and ?> tags. Generally, PHP files are either pure PHP-only, OR they are a mix of HTML and PHP, with the PHP code included on the page between these tags.
Here is a basic tutorial to give you an idea how it would work:
https://daveismyname.blog/creating-an-image-gallery-from-a-folder-of-images-automatically
What you can do is create an endpoint that would point out all the files that you need to display and make an API call to the endpoint using JS

Including JS file in JS code

I have a requirement of including a .js file (more jQuery code) at a run time in a currently working jQuery script. For example, if my page gets authenticated, then I want to include a particular script file. I want to do this in ASP.Net MVC.
Is there a way to do this? If so, what path do I give when calling that file?
I googled $.getScript('file_path'); but my page is getting refreshed in a loop, I don't why! Maybe I'm doing something wrong in path.
Any help would be much appreciated! Thank you.
Try this Including a .js file within a .js file
Basically, create script tag, append it so that it is read before the one that requires it & load the needed .js
//Load JS files as following
["../common/howler.min.js","js/min.js"].forEach(function (src) {
var script = document.createElement('script');
script.src = src;
script.async = false;
document.head.appendChild(script);
});
$.getScript() is exactly what you should use for this.
I want to call it in $.getScript();, what path should I give? like - "~/Scripts/content.js" or something else?
The issue there is because the tilde character (~) is an ASP.Net MVC construct which will not work in Javascript. For JS you need to use a relative path, for example:
$.getScript('/basefolder/foo.js');
Added correct path and it worked with "$.getScript();"

Using socket.io with a standalone javascript file

I'd like to use socket.io in a javascript file. How can I do this?
The only way I currently know of using socket.io, as a client is doing
<script src="[server?]/socket.io/socket.io.js"></script> inside an html file.
Including a javascript within a javascript file is not naturally accomplished, because it's not really needed in most scenarios (you just include them both on your html page, for example). You probably have to rethink the way you're executing javascript, but I do believe there is a library designed to this (for whatever reason that may be).
include.js I think it is called.
EDIT: and in the event you're thinking dynamically adding javascript, you can just create a script element and append it to document.head. Um, for example:
document.head = document.head || document.getElementsByTagName('head')[0];
var js = document.createElement('script');
js.setAttribute('type','text/javascript');
js.setAttribute('src','http://my/src/file');
document.head.appendChild(js);
...just off the top of my head.
In my html file I did:
<script src="http://[node server]:[port]/socket.io/socket.io.js"></script>
`
and in my .js file, I did
io.socket = io.connect('http://[node server]:[port]');
and it worked.
I suppose "a standalone javascript file" is inaccurate, because I'm building a web front-end. I meant that it was just a .js file with nothing like node.js running it.

Using Struts tags in Javascript

We have some widgets developed using Dojo and Javascript. The dojo code invokes some application services using io script mechanism to overcome cross browser issues. Currently the action for the io script is hard coded as follows.
var host="myhost.com";
var url = "http://"+host+"/context/service";
Every time we need to create WAR, we have to change host details. Is there a way in JS we can configure this ie., some thing like reading it from properties.
I found this s:url struts tag. I assume we can use this tag inside javascript code in a JSP. Can i use it in plain JS out side of JSP?
Sure, if you have your container set up to process *.js files as JSP files.
IMO this is a bit brittle.
You can also do things like hide data in the DOM via hidden elements or <script> tags with reasonable type attributes (e.g., not "text/javascript", the default).
You can also put the data into JavaScript variables in the JSP and access them from external JS files.

Categories