How to insert external stylesheet in JavaScript (dynamically) - javascript

...with right path.
For example. I have script called foo.js. I'd like to insert stylesheet declaration which I can do with following instruction:
$('head').append('<link rel="stylesheet" href="/template/foo.css" type="text/css" />');
Problem: I have to put full path to the stylesheet file. So instead of /template/foo.css I have to put: http://hostname/directory/template/foo.css. I can't set it statically beacause script can be placed in different servers and different locations. So it can be: http://foo.com/bar/foo.css or http://foo.com/foo.css.
It would be very useful if I can get path of foo.js file on the server. That would be good enough beacause then I could set stylesheet location based on the javascrpt's file.

I've always done:
$('body').append('<link rel="stylesheet" href="/template/foo.css" type="text/css" />');
instead of head
Ahh... sorry I just realised what your problem is. One strategy is to extract the path of the script from the DOM itself:
$('script').each(function(i,el){
var path = el.src.match(/^(.+)\/foo.js$/);
if (path) {
$('body').append('<link rel="stylesheet" ' +
'href="' + path[1] + '/foo.css" ' +
'type="text/css" />'
);
}
})

This is a common technique that I use to get the current script url:
var scriptUrl = (function() {
var scripts = document.getElementsByTagName('script'),
script = scripts[scripts.length - 1];
return script.src;
})();
It works basically because when the script is being executed, it is the last script tag on the DOM.

You can use window.location and obtain the path from that. For example for this page it is:
>>> window.location
http://stackoverflow.com/questions/2033742/how-to-insert-external-stylesheet-in-javascript-dynamically

Related

JavaScript getting filename without extension located in different folder

I would like to define a variable, which will include my filename only without any extension.
The example of my file is linked to the index.html page and it looks like this:
<script src="js/20231014.js" type="text/javascript"></script>
<script src="js/20211204.js" type="text/javascript"></script>
<script src="js/20230423.js" type="text/javascript"></script>
about 50 more files like these
so I want in my variable only the "20231014" extracted.
I found some nice solutions here:
How to get the file name from a full path using JavaScript?
from where I tried:
var filename = fullPath.replace(/^.*[\\\/]/, '')
but I got an error, that fullPath is not defined. That has led me to this link,
where I tried:
var fullPath = FileSystemEntry.fullPath;
but unfortunately, the error just changed, that fileSystemEntry is not defined.
My another approach was:
var fileurl = '/js/'.replace(/\.[^.]+$/, '')
where I got nothing
and finally
var fileurl = window.location.pathname;
where I got just index.html instead
Is there any swift solution for extracting the given filename from the link based in the other directory?
This code will do what you're after.
First we find the position of the last / character appearing in the
file-path.
Then we get the string that appears after the last / in the path.
Next we replace the '.js' part with nothing.
I've only performed a single check. That avoids printing an empty string for the script element that does all the work, since it's in the document and doen's have a source.
You'll need to add error-checking before this code is any good.
<head>
<script src="js/20231014.js" type="text/javascript"></script>
<script src="js/20211204.js" type="text/javascript"></script>
<script src="js/20230423.js" type="text/javascript"></script>
<script>
"use strict";
window.addEventListener('load', onLoad, false);
function onLoad(evt) {
let scripts = document.querySelectorAll('script');
scripts.forEach(scr => {
if (scr.src != '') {
let slashPos = scr.src.lastIndexOf('/');
let filename = scr.src.slice(slashPos + 1);
filename = filename.replace('.js', '');
console.log(filename);
}
});
}
</script>
</head>

Can I use JavaScript to change the JavaScript files a HTML document accesses?

I am trying to write a HTML page that asks users a series of questions. The answers to these questions are evaluated by my JavaScript code and used to determine which additional JavaScript file the user needs to access. My code then adds the additional JavaScript file to the head tag of my HTML page. I don't want to merge the code into a single JavaScript file because these additional files are large enough to be a nightmare if they're together, and I don't want to add them all to the head when the page first loads because I will have too many variable conflicts. I'm reluctant to redirect to a new webpage for each dictionary because this will make a lot of redundant coding. I'm not using any libraries.
I begin with the following HTML code:
<head>
<link rel="stylesheet" type="text/css" href="main.css">
<script src="firstSheet.js" type="text/JavaScript"></script>
</head>
//Lots of HTML.
<div id="mainUserMenu">
</div>
And I have the following JavaScript function:
function thirdLevelQuestions(secondLevelAnswer) {
//Code here to calculate the variables. This part works.
activeDictionary = firstKey + secondKey + '.js';
//Changing the HTML header to load the correct dictionary.
document.head.innerHTML = '<link rel="stylesheet" type="text/css" href="main.css"><script src="' + activeDictionary + '" type="text/JavaScript"></script><script src="firstSheet.js" type="text/JavaScript"></script>';
//for loop to generate the next level of buttons.
for (var i = 0; i < availableOptions.length; i++) {
document.getElementById('mainUserMenu').innerHTML += '<button onclick="fourthLevelQuestions(' + i + ')">' + availableOptions[i] + '</button>';
}
}
This creates the buttons that I want, and when I inspect the head element I can see both JavaScript files there. When I click on any of the buttons at this level they should call a function in the second file. Instead Chrome tells me "Uncaught ReferenceError: fourthLevelQuestions is not defined" (html:1). If I paste the code back into firstSheet.js the function works, so I assume the problem is that my HTML document is not actually accessing the activeDictionary file. Is there a way to do this?
What Can be done
You are trying to load Javascript on Demand. This has been a well thought out problem lately and most of the native solutions didn't work well across bowser implementations. Check a study here with different solutions and background of the problem explained well.
For the case of large web applications the solution was to use some javascript library that helped with modularising code and loading them on demand using some script loaders. The focus is on modularizing code and not in just script loading. Check some libraries here. There are heavier ones which includes architectures like MVC with them.
If you use AJAX implementation of jQuery with the correct dataType jQuery will help you evaluate the scripts, they are famous for handling browser differences. You can as well take a look at the exclusive getScript() which is indeed a shorthand for AJAX with dataType script. Keep in mind that loading script with native AJAX does not guarantee evaluation of the javascript included, jQuery is doing the evaluation internally during the processing stage.
What is wrong
What you have done above might work in most modern browsers (not sure), but there is an essential flaw in your code. You are adding the script tags to your head using innerHTML which inserts those lines to your HTML. Even if your browser loads the script it takes a network delay time and we call it asynchronous loading, you cannot use the script right away. Then what do you do? Use the script when its ready or loaded. Surprisingly you have an event for that, just use it. Can be something like:
var head= document.getElementsByTagName('head')[0];
var script= document.createElement('script');
script.type= 'text/javascript';
script.onreadystatechange= function () {
if (this.readyState == 'complete') helper();
}
script.onload= helper;
script.src= 'helper.js';
head.appendChild(script);
Check this article for help with implementation without using external libraries
From the variable name activeDictionary If I guess that you are loading some data sets as opposed to javascript programs, you should try looking into JSON and loading and using them dynamically.
If this Question/Answer satisfies your needs, you should delete your question to avoid duplicate entries in SO.
The best way to achieve this would be with jQuery:
$(document).ready(function() {
$('#button').click(function() {
var html = "<script src='newfile.js' type='text/javascript'></script>";
var oldhtml = "<script src='firstSheet.js' type='text/javascript'></script>";
if ($(this).attr('src') == 'firstSheet.js') {
$('script[src="firstSheet.js"]').replace(html);
return;
}
$('script[src="newfile.js"]').replace(oldhtml);
});
});
I would suggest you create the elements how they should be and then append them. Also, if you are dynamically adding the firstSheet.js you shouldn't include it in your .html file.
function thirdLevelQuestions(secondLevelAnswer) {
var mainUserMenu = document.getElementById('mainUserMenu');
activeDictionary = firstKey + secondKey + '.js';
var css = document.createElement('link');
css.rel = 'stylesheet';
css.type = 'text/css';
css.href = 'main.css';
var script1 = document.createElement('script');
script1.type = 'text/javascript';
script1.src = 'firstSheet.js';
var script2 = document.createElement('script');
script2.type = 'text/javascript';
script2.src = activeDictionary;
document.head.appendChild(css);
document.head.appendChild(script1);
document.head.appendChild(script2);
for (var i = 0; i < availableOptions.length; i++) {
var btn = document.createElement('button');
btn.onclick = 'fourthLevelQuestions(' + i + ')';
var val = document.createTextNode(availableOptions[i]);
btn.appendChild(val);
mainUserMenu.appendChild(btn);
}
}

Jquery - reload css with google fonts link

I need to reload css files after the user select his theme colors with colorpicker.
Into another question here i found this good solution :
/**
* Forces a reload of all stylesheets by appending a unique query string
* to each stylesheet URL.
*/
function reloadStylesheets() {
var queryString = '?reload=' + new Date().getTime();
$('link[rel="stylesheet"]').each(function () {
this.href = this.href.replace(/\?.*|$/, queryString);
});
}
my problem is that i have a google fonts linked into the pages
<link href='http://fonts.googleapis.com/css?family=Varela+Round' rel="stylesheet">
and in console i recieve this error :
Failed to load resource: the server responded with a status of 400 (Bad Request)
http://fonts.googleapis.com/css?reload=1397489335832
The other css stored into my server are reloaded well.
e.g. <link href="css/style.css" rel="stylesheet" type="text/css" />
How i can "separate" the stylesheet google from the others ?
Your link to the fonts is http://fonts.googleapis.com/css?family=Varela+Round, therefore your reload link should be http://fonts.googleapis.com/css?family=Varela+Round&reload=1397489335832
You need to update your function to take into account cases where there is already a parameter in the URL.
function reloadStylesheets() {
var queryString = 'reload=' + new Date().getTime();
$('link[rel="stylesheet"]').each(function () {
if(this.href.indexOf('?') !== -1){
this.href = this.href + '&' + queryString;
}
else{
this.href = this.href + '?' + queryString;
}
});
}
You can test for the google stylesheet link easily enough:
var googleUrl = new RegExp('fonts.googleapis.com/css\\?family=Varela\\+Round');
$('link[rel="stylesheet"]').each(function () {
if (googleUrl.test(this.href)) {
continue;
}
However, the root problem is that your reloadStylesheets function is too aggressive in replacing the queryString. Instead of blindly replacing everything after the question mark with your new reload parameter, you should be more precise. That way, if you ever load a local stylesheet where the query string is important (e.g., a server-generated style sheet with only a subset of styles for mobile), you don't break your page with the script.
This will also obviate the need to exclude the Google stylesheet, but since it's unlikely that is going to change, you should continue to exclude it and let it load from browser cache.

Is there an easy way to reload css without reloading the page?

I'm trying to make a live, in-page css editor with a preview function that would reload the stylesheet and apply it without needing to reload the page. What would be the best way to go about this?
Possibly not applicable for your situation, but here's the jQuery function I use for reloading external stylesheets:
/**
* Forces a reload of all stylesheets by appending a unique query string
* to each stylesheet URL.
*/
function reloadStylesheets() {
var queryString = '?reload=' + new Date().getTime();
$('link[rel="stylesheet"]').each(function () {
this.href = this.href.replace(/\?.*|$/, queryString);
});
}
On the "edit" page, instead of including your CSS in the normal way (with a <link> tag), write it all to a <style> tag. Editing the innerHTML property of that will automatically update the page, even without a round-trip to the server.
<style type="text/css" id="styles">
p {
color: #f0f;
}
</style>
<textarea id="editor"></textarea>
<button id="preview">Preview</button>
The Javascript, using jQuery:
jQuery(function($) {
var $ed = $('#editor')
, $style = $('#styles')
, $button = $('#preview')
;
$ed.val($style.html());
$button.click(function() {
$style.html($ed.val());
return false;
});
});
And that should be it!
If you wanted to be really fancy, attach the function to the keydown on the textarea, though you could get some unwanted side-effects (the page would be changing constantly as you type)
Edit: tested and works (in Firefox 3.5, at least, though should be fine with other browsers). See demo here: http://jsbin.com/owapi
There is absolutely no need to use jQuery for this. The following JavaScript function will reload all your CSS files:
function reloadCss()
{
var links = document.getElementsByTagName("link");
for (var cl in links)
{
var link = links[cl];
if (link.rel === "stylesheet")
link.href += "";
}
}
A shorter version in Vanilla JS and in one line:
document.querySelectorAll("link[rel=stylesheet]").forEach(link => link.href = link.href.replace(/\?.*|$/, "?" + Date.now()))
It loops trough all stylesheet links and appends (or updates) a timestamp to the URL.
Check out Andrew Davey's snazzy Vogue project - http://aboutcode.net/vogue/
One more jQuery solution
For a single stylesheet with id "css" try this:
$('#css').replaceWith('<link id="css" rel="stylesheet" href="css/main.css?t=' + Date.now() + '"></link>');
Wrap it in a function that has global scrope and you can use it from the Developer Console in Chrome or Firebug in Firefox:
var reloadCSS = function() {
$('#css').replaceWith('<link id="css" rel="stylesheet" href="css/main.css?t=' + Date.now() + '"></link>');
};
Based on previous solutions, I have created bookmark with JavaScript code:
javascript: { var toAppend = "trvhpqi=" + (new Date()).getTime(); var links = document.getElementsByTagName("link"); for (var i = 0; i < links.length;i++) { var link = links[i]; if (link.rel === "stylesheet") { if (link.href.indexOf("?") === -1) { link.href += "?" + toAppend; } else { if (link.href.indexOf("trvhpqi") === -1) { link.href += "&" + toAppend; } else { link.href = link.href.replace(/trvhpqi=\d{13}/, toAppend)} }; } } }; void(0);
Image from Firefox:
What does it do?
It reloads CSS by adding query string params (as solutions above):
Content/Site.css becomes Content/Site.css?trvhpqi=1409572193189 (adds date)
Content/Site.css?trvhpqi=1409572193189 becomes Content/Site.css?trvhpqi=1409572193200 (date changes)
http://fonts.googleapis.com/css?family=Open+Sans:400,300,300italic,400italic,800italic,800,700italic,700,600italic,600&subset=latin,latin-ext becomes http://fonts.googleapis.com/css?family=Open+Sans:400,300,300italic,400italic,800italic,800,700italic,700,600italic,600&subset=latin,latin-ext&trvhpqi=1409572193189 (adds new query string param with date)
Since this question was shown in the stackoverflow in 2019, I'd like to add my contribution using a more modern JavaScript.
Specifically, for CSS Stylesheet that are not inline – since that is already covered from the original question, somehow.
First of all, notice that we still don't have Constructable Stylesheet Objects. However, we hope to have them landed soon.
In the meantime, assuming the following HTML content:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link id="theme" rel="stylesheet" type="text/css" href="./index.css" />
<script src="./index.js"></script>
</head>
<body>
<p>Hello World</p>
<button onclick="reload('theme')">Reload</button>
</body>
</html>
We could have, in index.js:
// Utility function to generate a promise that is
// resolved when the `target` resource is loaded,
// and rejected if it fails to load.
//
const load = target =>
new Promise((rs, rj) => {
target.addEventListener("load", rs, { once: true });
target.addEventListener(
"error",
rj.bind(null, `Can't load ${target.href}`),
{ once: true }
);
});
// Here the reload function called by the button.
// It takes an `id` of the stylesheet that needs to be reloaded
async function reload(id) {
const link = document.getElementById(id);
if (!link || !link.href) {
throw new Error(`Can't reload '${id}', element or href attribute missing.`);
}
// Here the relevant part.
// We're fetching the stylesheet from the server, specifying `reload`
// as cache setting, since that is our intention.
// With `reload`, the browser fetches the resource *without* first looking
// in the cache, but then will update the cache with the downloaded resource.
// So any other pages that request the same file and hit the cache first,
// will use the updated version instead of the old ones.
let response = await fetch(link.href, { cache: "reload" });
// Once we fetched the stylesheet and replaced in the cache,
// We want also to replace it in the document, so we're
// creating a URL from the response's blob:
let url = await URL.createObjectURL(await response.blob());
// Then, we create another `<link>` element to display the updated style,
// linked to the original one; but only if we didn't create previously:
let updated = document.querySelector(`[data-link-id=${id}]`);
if (!updated) {
updated = document.createElement("link");
updated.rel = "stylesheet";
updated.type = "text/css";
updated.dataset.linkId = id;
link.parentElement.insertBefore(updated, link);
// At this point we disable the original stylesheet,
// so it won't be applied to the document anymore.
link.disabled = true;
}
// We set the new <link> href...
updated.href = url;
// ...Waiting that is loaded...
await load(updated);
// ...and finally tell to the browser that we don't need
// the blob's URL anymore, so it can be released.
URL.revokeObjectURL(url);
}
i now have this:
function swapStyleSheet() {
var old = $('#pagestyle').attr('href');
var newCss = $('#changeCss').attr('href');
var sheet = newCss +Math.random(0,10);
$('#pagestyle').attr('href',sheet);
$('#profile').attr('href',old);
}
$("#changeCss").on("click", function(event) {
swapStyleSheet();
} );
make any element in your page with id changeCss with a href attribute with the new css url in it. and a link element with the starting css:
<link id="pagestyle" rel="stylesheet" type="text/css" href="css1.css?t=" />
<img src="click.jpg" id="changeCss" href="css2.css?t=">
Another answer:
There's a bookmarklet called ReCSS. I haven't used it extensively, but seems to work.
There's a bookmarklet on that page to drag and drop onto your address bar (Can't seem to make one here). In case that's broke, here's the code:
javascript:void(function()%7Bvar%20i,a,s;a=document.getElementsByTagName('link');for(i=0;i%3Ca.length;i++)%7Bs=a[i];if(s.rel.toLowerCase().indexOf('stylesheet')%3E=0&&s.href)%20%7Bvar%20h=s.href.replace(/(&%7C%5C?)forceReload=%5Cd%20/,'');s.href=h%20(h.indexOf('?')%3E=0?'&':'?')%20'forceReload='%20(new%20Date().valueOf())%7D%7D%7D)();
simple if u are using php
Just append the current time at the end of the css like
<link href="css/name.css?<?php echo
time(); ?>" rel="stylesheet">
So now everytime u reload whatever it is , the time changes and browser thinks its a different file since the last bit keeps changing.... U can do this for any file u force the browser to always refresh using whatever scripting language u want
In a simple manner you can use rel="preload" instead of rel="stylesheet" .
<link rel="preload" href="path/to/mystylesheet.css" as="style" onload="this.rel='stylesheet'">
Based on https://stackoverflow.com/a/59176853/3917091 on this page
function refreshStylesheets() {
// In my case, I'm getting all urls on my site (mysite.dev).
(document.querySelectorAll('link[rel="stylesheet"][href*="mysite.dev\/"],link[rel="stylesheet"][data-href*="mysite.dev\/"]') || []).forEach(async link => {
// Reload the file, by data-href first if it's available, otherwise use href
const reload = await fetch(link.dataset.href || link.href, { cache: "reload" }),
// Generate url
url = URL.createObjectURL(await reload.blob());
// preserve real url
if (!link.dataset.href) link.dataset.href = link.href;
link.href = url.toString();
});
}
The advantage this has, over appending to the url, is that this actually removes it from the browser cache. Using other scripts works great, but when you refresh the page, it reverts to what it had cached. Minor annoyance. However, this does not revert upon refresh.
It's a nice way to quickly change css for testing without ctrl F5 refresh all of the time, and then you roll out the change by server-side updating the filename or the query string on the style sheet as normal.
The data-href 'preserving' is important, or the permanency of refreshing on your cache only works once per page-view.
The same sort of script can be written for script[src] but I would not advise that, because you may end up with all kinds of bugs with certain things being done twice, like event listeners.
Yes, reload the css tag. And remember to make the new url unique (usually by appending a random query parameter). I have code to do this but not with me right now. Will edit later...
edit: too late... harto and nickf beat me to it ;-)

~/ equivalent in javascript

Any smart way of doing a "root" based path referencing in JavaScript, just the way we have ~/ in ASP.NET?
Have your page generate a tag with something like:
<link rel="home" id="ApplicationRoot" href="http://www.example.com/appRoot/" />
Then, have a function in JavaScript that extracts the value such as:
function getHome(){
return document.getElementById("ApplicationRoot").href;
}
Use base tag:
<head>
<base href="http://www.example.com/myapp/" />
</head>
...
from now any link use on this page, no matter in javascript or html, will be relative to the base tag, which is "http://www.example.com/myapp/".
You could also use the asp.net feature VirtualPathUtility:
<script>
var basePath = '<%=VirtualPathUtility.ToAbsolutePath("~/")%>';
</script>
Notice: I don't encode the path to a JSON-string (escape quotes, control characters etc). I don't think this is a big deal (quotes for example aren't allowed unescaped in an URL), but one never knows...
I usually create a variable at the top of the js file and assign it the root path. Then I use that variable when referencing a file.
var rootPath = "/";
image.src = rootPath + "images/something.png";
~/ is the application root and not a literal root, it interpets ~/ to mean <YourAppVirtualDir>/
To do a literal root in JavaScript it's just /, i.e "/root.html". There's no way of getting an application level path like that in JavaScript.
You could hack it in the ASPX file and output it in a tag but I would consider the security implications of that.
Kamarey's answer can be improved to support a dynamic base path:
<head>
<base href="http://<%= Request.Url.Authority + Request.ApplicationPath%>/" />
</head>
This will ensure a correct root path regardless of deployment configuration.
To be fair, this doesn't answer the original question, but it elimiates most needs for getting the root path from javascript. Simply use relative URL's everywhere, without prefixing with slash.
Should you still need to access it from javascript, add an id attribute and use document.getElementFromId() as MiffTheFox suggested - but on the base-tag.
Another option that's a bit simpler and more universal would be to take the following:
<script src="/assets/js/bootstrap.min.js"><script>
and use Page.ResolveClientUrl like so:
<script src='<%=ResolveClientUrl("~/assets/js/bootstrap.min.js")%>'></script>
then regardless of what subdirectory the urls will always be rendered correctly.
The following function will calculate the root of the currently running application. I use it to locate the absolute location of resources, when called from somewhere deep within the application tree.
function AppRoot() {
//
// Returns the root of the currently running ASP application.
// in the form: "http://localhost/TRMS40/"
//
// origin: "http://localhost"
// pathname: "/TRMS40/Test/Test%20EMA.aspx"
//
// usage:
// window.open( AppRoot() + "CertPlan_Editor.aspx?ID=" + ID);
//
var z = window.location.pathname.split('/');
return window.location.origin + "/" + z[1] + "/";
}
In the PreRender of your .NET base page, add this:
protected override void
OnPreRender(EventArgs e) {
base.OnPreRender(e);
if (Page.Header != null)
{
//USED TO RESOLVE URL IN JAVASCRIPT
string baseUrl = String.Format("var baseUrl='{0}';\n",
HttpContext.Current.Request.ApplicationPath);
Page.Header.Controls.Add(new LiteralControl(String.Format(Consts.JS_TAG,
baseUrl)));
}
}
Then in your global JavaScript function, add the following:
function resolveUrl(url) {
if (url.indexOf("~/") == 0) {
url = baseUrl + url.substring(2);
}
return url; }
Now you can use it like this:
document.getElementById('someimage').src = resolveUrl('~/images/protest.jpg');
May be a little much for some projects, but works great for full fledged applications.
Solution for ASP.NET MVC applications
This works when using IIS and also IIS Express in VS.
Put this snippet before all scripts load, in order to have the root url variable "approot".
at your service in the scripts:
<script>
var approot = "#Url.Content("~")";
</script>
--> other scripts go here or somewhere later in the page.
Then use it in your script or page script.
Example:
var sound_root_path = approot + "sound/";
var img_root_path = approot + "img/";
the approot variable will be something either:
"/YourWebsiteName/" <-- IIS
or just:
"/" <-- IIS Express
For ASP.net MVC Razor pages, Create a base tag like below in the <Head> tag
<base href="http://#Request.Url.Authority#Request.ApplicationPath" />
and in all your relative javascript URLs, make sure to start without a slash(/) otherwise it will refer from the root.
For ex. create all your urls like
"riskInfo": { url: "Content/images/RiskInfo.png", id: "RI" },
or
$http.POST("Account/GetModelList", this, request, this.bindModelList);
If you want to use it in HTML Still you can use ~, see this
href = #Url.Content("~/controllername/actionName")
See the check box click event in my MVC Application
#Html.CheckBoxFor(m=>Model.IsChecked,
new {#onclick=#Url.Content("~/controller/action("+ #Model.Id + ", 1)"),
#title="Select To Renew" })

Categories