I have a site that requires two themes to be loaded. The second theme can be toggled on/off by the user. I'm currently accomplishing this by using the disabled
tag in the link like so:
<link rel="stylesheet" href="{{main css}}">
<link rel="stylesheet" title="theme-white" href="{{2nd theme css}}" disabled>
I then toggle disabled
in JavaScript.
This works great in Safari (Mac), Chrome (Mac/Windows), and IE10. However, Firefox (both Mac and Windows) seems to ignore the disabled
tag on page load and displays the second theme on initial load (as it is loaded second). When I manually toggle disabled
, however, Firefox does respond to the tag and will begin to switch the second theme on/off.
How can I accomplish this goal?
I found a workaround that seems to be functional in all browsers. This does NOT seem like it should be the best way to do it but I wanted to share.
This is not ideal for a few reasons but I tried to make it streamlined and without any external library dependency like jQuery because this needs to be placed in your head
tag and you probably have not loaded your JS libraries at that point.
<script>
window.onload = function() {
var path = "css";
var style = document.createElement( 'link' );
style.rel = 'stylesheet';
style.href = '/your/css/url.css';
document.getElementsByTagName( 'head' )[0].appendChild( style );
style.disabled = true;
};
</script>
NOTE: Firefox seems to only respond to the disabled tag if it is applied to the stylesheet after it has been added to the DOM. I still feel like I'm missing something because that seems crazy.
So, if you were to put style.disabled = true;
before you add the style to your document then Firefox does not recognize the disabled state of the stylesheet.
This is fixed in Firefox 68. You can now set the disabled
attribute on <link>
elements that also contain the ref=stylesheet
attribute value. This will prevent the browser from loading that stylesheet until the disabled
attribute is set to false
or removed via JavaScript or some other method.
This brings Firefox in line with Chrome, Edge, Safari on support for this feature.
More info on MDN: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link#Attributes
Bugzilla report: https://bugzilla.mozilla.org/show_bug.cgi?id=1281135
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With