Ekata
Ekata

Reputation: 289

Can I call a JavaScript function inside a <link> tag href?

I have a CSS file I need to load with an included version:

 <link rel="stylesheet" href="../assets/css/jquery-ui.css?="+getVersion()/>

where getVersion() is a function that returns the version, but this is not working.

I also tried with:

<link rel="stylesheet" href="../assets/css/bootstrap.css?=javascript:getAppVersion()">

Upvotes: 0

Views: 1133

Answers (1)

Timusan
Timusan

Reputation: 3445

As stated in my comment, you will need to include the whole <link> tag using JavaScript in order to have it act "dynamically". You cannot just tack JavaScript code into HTML without any encapsulation.

Blatantly assuming you are using jQuery, this is one way to go about it:

$( document ).ready(function() {

    /* Definition of getVersion() here*/

    $('head').append('<link rel="stylesheet" href="../assets/css/jquery-ui.css?='+getVersion()+'/>');
});

This will simply add the string which contains the <link> with the correct version number to the <head> of your document.

Note that the stylesheet is appended when your DOM is finished loading, so you might see a short glitch of unstyled markup.

Of course, it may be best to include the version number server side if possible, this would (for one) take care of the possible glitch as the correct <link> tag (version number) is available during building of the DOM.

Upvotes: 2

Related Questions