Logo Questions Linux Laravel Mysql Ubuntu Git Menu

Append timestamp on src or href attribute with JavaScript

For 2 days I've been looking an answer, but I can't find a good solution to my problem.

I'm developing a web application where I can only use standard front-end files (HTML, CSS, JavaScript (I use jQuery)). There's no back-end script merged with the HTML.

What I'm trying to achieve is to add an <script> tag to my HTML, but with a timestamp added as a variable, such as: <script type="text/javascript" src="js/javascript.js?c=1421656264439"></script>.

With PHP it would be simple to achieve, because you can just add the timestamp along with the HTML. But since I must work with front-end code only, what would be the best way to add a script or link tag with a timestamp, so the script doesn't get loaded from the cache?

Since the client uses Internet Explorer 10, I will need an answer that will work with that...

Could anyone help me out?

like image 529
Guido Visser Avatar asked Mar 17 '23 15:03

Guido Visser

2 Answers

While creating an element, setting the attributes and appending it to the document kind of worked, the beforeSend headers weren't set on the AJAX calls in the javascript.js for some reason. This was also the issue by using $.getScripts('js/javascript.js');

I suddenly realised that I could try a simple document.write() within a script tag. Turns out that it works like a charm.

My fix:

    <script type="text/javascript">
        var _c = new Date().getTime();
        document.write('<script type="text/javascript" src="js/javascrtipt.js?c='+_c+'"><\/script>');

(I can't believe I couldn't come up with this solution earlier)

like image 200
Guido Visser Avatar answered Mar 27 '23 18:03

Guido Visser

Since you are working with jQuery I recommend you to do it this way:

$.getScript( "js/javascript.js" );

From jQuery docs:

By default, $.getScript() sets the cache setting to false. This appends a timestamped query parameter to the request URL to ensure that the browser downloads the script each time it is requested.

like image 35
Mario A Avatar answered Mar 27 '23 18:03

Mario A