Chrome sometimes not requesting CSS pages - javascript

This is an ASPX page and rarely the stylesheets do not load. No Request either. I can look at the network log in chromes debug and see that it didnt request it or load it from cache. Everything else, img , js, whatever all loads without problem. The only thing that this site does that I have never done before is load a stylesheet via javascript and that will request and work every time. There is also an Iframe in the page and that css always works as well. It feels like a 1 in 10 chance for this to happen, but its random. I cant remember if it happens when i run it locally or not, but it will happen on the 3 different IIS servers. In the sources of the Chrome DevTools it shows the file in there as well. Is this a bug in chrome or something? Is it a weird thing with closing tag in the links? Has anyone seen this before?
<head>
....
<link type="text/css" rel="stylesheet" href="~/css/site.min.css?v=#Model.buildTag" />
<link href="~/lib/tabulator/css/tabulator.css" rel="stylesheet" />
<link id="glcss" type="text/css" rel="stylesheet" href="/css/empty.css">
</head>
This JS code runs mid way trough the initial js load of the page before doc render and it sets a stylesheet to the page. Not sure if this would cause chrome to randomly abandon the other css documents. This css always works.
var stylesheetPath = _pth + "/css/custom_gl_theme_" + dd.value + ".min.css?v=" + _v;
$('link[id="glcss"]').attr('href', stylesheetPath);
this.value = dd.value;

Still don't know the cause, but this is the solution we had put in place. Basically, once the page loads, we check to see if those css files loaded properly, and if not, reset the url and it would force the pull.
$(window).on('load', function (e) {
var links = document.getElementsByTagName('link');
for (var i = 0, linkLen = links.length; i < linkLen; i++) {
var link = links[i];
if ((link.id == "") && (link.type == "text/css")) {
var cssHref = link.href;
link.href = cssHref;
}
}
});

Related

How do I retain toggle state across website?

So, I have a button that toggles between dark and light mode (my site is dark by default) and it works but now I need it to stay on whatever toggle state is selected across multiple pages. I suspect it has something to do with sessionstorage. Not using jQuery and don't want to. What can I just add to my code to make that happen?
I have five pages all linked to styles.css with an id of "dark" and then in the JS I'm referencing a second style sheet, light.css or 'light' in the JS, so I'm toggling the style sheets. All five pages have the button in the footer each with the same function written in one JS file.
HTML
<head>
<link rel="stylesheet" href="styles.css" id="dark">
</head>
<body>
<button onclick="toggle();" id="light-mode"><i class="fas fa-adjust"></i></button>
</body>
JavaScript
function toggle() {
var a = document.getElementById("dark");
a.x = 'light' == a.x ? 'styles' : 'light';
a.href = a.x + '.css';
}
This works perfectly, just not sure how to integrate sessionstorage or localstorage to save the toggle state across the site. What is the best method proceeding from this point if possible or should I do a complete overhaul?
UPDATE
So, tried #Reality's answer and not working but I think I might just be integrating it wrong. Very new to JS.
localStorage.setItem('toggled','true');
function toggle() {
var a = document.getElementById("dark");
a.x = 'light' == a.x ? 'styles' : 'light';
a.href = a.x + '.css';
if (localStorage.getItem('toggled') === 'false') {
localStorage.setItem('toggled','true');
} else {
localStorage.setItem('toggled','false');
}
}
SOLVED
Ok, anyone wanting to know how to toggle a theme perfectly where it works across your website, just follow this: https://dev.to/albertomontalesi/add-dark-mode-to-your-website-with-just-a-few-lines-of-code-5baf
When you follow that, you should do an additional thing to have your theme load better when toggled to. Just link to your second style sheet in the head of every page and add disabled="disabled" If you don't add this to the above approach, I found that when toggling to whatever theme and then navigating around the site, you basically have to load a new style sheet and you get a flicker and can even see the bare HTML version of the site momentarily, so this addition fixes that because by putting it in the head it is already loaded from the beginning.
FINAL
Here's what ended up working:
<head>
<link rel="stylesheet" href="dark-theme.css" type="text/css" id="theme">
<link rel="stylesheet" href="light-theme.css" type="text/css" disabled="disabled">
<script>
document.addEventListener('DOMContentLoaded', () => {
const themeStylesheet = document.getElementById('theme');
const storedTheme = localStorage.getItem('theme');
if (storedTheme) {
themeStylesheet.href = storedTheme;
}
const themeToggle = document.getElementById('theme-toggle');
themeToggle.addEventListener('click', () => {
if (themeStylesheet.href.includes('dark')) {
themeStylesheet.href = 'light-theme.css';
} else {
themeStylesheet.href = 'dark-theme.css';
}
localStorage.setItem('theme', themeStylesheet.href);
});
});
</script>
</head>
Per #Reality's suggestion, placing the JS in the head improved performance better than what the SOLVED edit suggested doing, however, the code in the link provided (https://dev.to/albertomontalesi/add-dark-mode-to-your-website-with-just-a-few-lines-of-code-5baf) is what is used in the above example. Still needed the disabled="disabled" in the light-theme.css link or else it would override the dark-theme.css and the toggle wouldn't occur all together. This was true of all the code examples seen in this thread that were tried.
You can set it using localStorage.setItem(); and localStorage.getItem().
localStorage.setItem('toggled','true');
//or
localStorage.setItem('toggled','false');
inside your toggle function:
//get the style by it's id
let a = document.getElementById("dark");
if(localStorage.getItem('toggled') === 'false'){
//set toggled to true, because the user clicked it when dark theme is on
localStorage.setItem('toggled','true');
//toggled is now on, in this case, light theme is switched on
//do something here
a.href = "light.css";
}
else{
//set toggled to false, because the user clicked it when light theme is on
localStorage.setItem('toggled','false');
//if toggled is off, in this case, dark theme is switched on
a.href = "styles.css";
}
It seems confusing at first, but just pay attention to the logic. It'll start to unfold in your mind as you read and reread it :)
If you want to switch to session storage (for that tab instance. Once you close the tab, session storage for that tab is deleted), then just replace the "localStorage" with "sessionStorage". Please keep in mind that localStorage and sessionStorage stringify values (convert them into a string) before storing them.

Why document.styleSheets[0].href doesn't get updated?

Why document.styleSheets[0].href doesn't get updated but document.getElementsByTagName('link')[0].href does, when I dynamically create a <base/> tag?
On Opera it works fine, but Firefox and Chrome don't update the value.
Here is the code, you can run it on http://jsfiddle.net/XcDCk/.
If you don't run it on jsfiddle.net you must add a linked stylesheet (<link rel="stylesheet" type="text/css" href="styles.css"/>)
var base = document.createElement('base');
base.href = 'http://google.com/';
document.getElementsByTagName('head')[0].appendChild(base);
var link = document.getElementsByTagName('link')[0];
alert('Link: '+link.href);
var styleSheet = document.styleSheets[0];
alert('Stylesheet: '+styleSheet.href);
var hojaEstilos = document.styleSheets[0];
alert('Stylesheet + ownerNode: '+hojaEstilos.ownerNode.href);
I could get it done (on the third alert) by using the ownerNode attribute (which is actually the link element, so I can get the same result as the first alert), but I can't understand why the second alert doesn't work.
Thank you

Problems with SoundManager 2

I am trying to implement SoundManager 2 to play snippets of songs on this page.
This is my current JavaScript code:
alert('c!');
soundManager.url = 'http://www.transapine.ch/common/soundmanagerv297a-20120513/swf/soundmanager2.swf';
soundManager.flashVersion = 8; // optional: shiny features (default = 8)
soundManager.useFlashBlock = false; // optionally, enable when you're ready to dive in
/*
Example HTML to make sound snippet:
<div>
<img src="..." height="x" />
</div>
*/
alert('d!');
soundManager.onready(function() {
alert('e!');
var els = $.Elements.getElementsByClassName('sclip');
var a = url = '';
var clips = new Array();
var masterVolume = 100;
for (var i=0; i<els.length; i++) {
a = els[i];
url = a.href;
clips[i] = soundManager.createSound({
id: "clip" + i,
url: url,
volume: masterVolume
});//clips[i] = soundManager.createSound({
$.Events.add(a, "click", function(e) {
e.preventDefault();
clips[i].play();
});//$.Events.add(el, "click", function() {
$.CSS.removeClass(a, 'hidden');// show the button
}//for (var i=0; i<els.length; i++) {
});//soundManager.onready(function() {
And this is the section in the HTML page calling the necessary scripts:
<script src="http://assets.momo40k.ch/common/js/$-min.js" type="text/javascript"></script>
<script type="text/javascript">alert('a!'); //these alerts are for debugging</script>
<script src="http://assets.momo40k.ch/common/soundmanagerv297a-20120513/script/soundmanager2-nodebug-jsmin.js" type="text/javascript"></script>
<script type="text/javascript">alert('b!');</script>
<script src="http://assets.momo40k.ch/common/js/soundclips.js" type="text/javascript"></script>
<script type="text/javascript">alert('f!');</script>
Note: the $ library is a small library I use to even out the browser differences.
I have encountered several problems with this.
1. SWF files
In SoundManager's tutorial it says to use soundManager.url to tell it the location of the SWF files it needs. Whatever value I gave it, it seemed to ignore it, as Firebug gave me the following error:
NetworkError: 404 Not Found - http://www.transalpine.ch/portale/soundmanager2.swf
So I tried putting soundmanager2.swf in http://www.transalpine.ch/portale/, and the error disappeared, so I continued to see if I could get it to work like this.
Note: I have a base tag setting http://www.transalpine.ch/portale/ as the base URL in this section of the site.
Problems 2 and 3 sort of happened at the same time, I only managed to separate them through debugging the script little by little...
2. Script doesn't execute in certain conditions
After that, nothing happened. The two testing buttons I had put on the page weren't appearing as they should be ($.CSS.removeClass(a, 'hidden'); removes the class hidden from the elements, effectively showing them), so I went about working out what was executing and what wasn't in my usual way: alerts!
So I found out that soundclips.js wasn't executing at all, and then I found out that it could execute as long as lines 28-32 (clips[i] = soundManager.createSound({...});) were commented out. That puzzled me: how can something the browser hasn't even read yet prevent from reading that whole file?!
3. soundManager.onready doesn't fire
Having removed those lines, I still had a last problem, though probably it's caused by problem 1: the event soundManager.onready never fires.
Does anyone know what's wrong with my setup, and what's causing all these problems?
I'm guessing 2 and 3 both derive from 1, but I really don't understand 1 nor how 2 can be...
Thank you!
First off the URL should look like this:
soundManager.url = 'http://www.transapine.ch/common/soundmanagerv297a-20120513/swf/';
Everything else should somewhat be fixed now.

jquery issues - it wont change it accordingly

My coding isnt linking properly , its meant to use jquery to detect the OS and change the link accordingly , however it isn't.
In my HTML page I have it linked in the header as
<script src="jsquery.js" type="text/javascript"></script>
which loads up my jsquery now
$(document).ready(function() {
if (navigator.appVersion.indexOf("Win") != -1) {
// Computers runs windows
$("a[href$='.pdf']").each(function() {
this.href = this.href.replace("Volumes", "KP01DS0194TG");
});
}
if (navigator.appVersion.indexOf("Mac") != -1) {
// computer is a Mac
$("a[href$='.pdf']").each(function() {
this.href = this.href.replace("KP01DS0194TG", "Volumes");
});
}
});
Yet on Mac's it still tries to connect to KP01DS0194TG and not to Volumes - it doesnt change it - how can I get it to recognize the OS and change it accordingly?
I believe that you are improperly linking to jquery. I would think it should be jquery.js not jsquery.js. Try changing the link in the header to this:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>

cant print images with JavaScript print function

I am trying to print a report which includes text and images. I am using a javascript function to invoke the print functionality. Everything works well except the images on the page do not show up in the new print window. I have included all the CSS files with it but still my images dont appear in the new print window. Its the same even if I dont include the CSS links.
My javascript function to print is :
function printfun(){
var disp_setting = "toolbar=no,location=no,directories=no,menubar=no,";
disp_setting += "scrollbars=no,left=0,top=0,resizable=yes,width=900 height=650,modal=yes,";
var content_vlue = document.getElementById('<%= tblCharts.ClientID %>').innerHTML;
var docprint = window.open("", "", disp_setting);
docprint.document.write('<html><head>');
docprint.document.write('</head>');
docprint.document.write('<body onLoad="self.print()">');
docprint.document.title = "";
docprint.document.write('<link href="../style/design.css" rel="Stylesheet" type="text/css" />');
docprint.document.write('<link href="../App_Themes/style/graphs.css" rel="Stylesheet" type="text/css" />');
docprint.document.write(content_vlue);
docprint.document.write(tblCharts);
docprint.document.write("</body></html>");
docprint.document.close();
docprint.focus();
}
Are the images background images in the CSS? If so, the browser likely isn't set to print those by default. That'd a browser setting the user would have to change.

Categories