Dynamic CSS loading often proves invaluable for creating responsive designs that minimize page-load latency. However, when using this technique, users often find that their styles only apply to some of their chosen browsers.
In the example below, the CSS styles are successfully loaded in Firefox and Google Chrome but fail to load in Internet Explorer (IE).
var head = document.getElementsByTagName('head')[0]; $(document.createElement('link')) .attr({ type: 'text/css', href: '../../mz/mz.css', rel: 'stylesheet' }) .appendTo(head);
Solution:
The difference arises from the way that IE handles stylesheet processing. Unlike other browsers, IE only allows stylesheet attachment once its built-in style engine has parsed all of the styles loaded with the page. To circumvent this, we leverage the document.createStyleSheet(url) method, which reliably adds the stylesheet during the loading process.
url = 'style.css'; if (document.createStyleSheet) { document.createStyleSheet(url); } else { $('<link rel="stylesheet" type="text/css" href="' + url + '" />').appendTo('head'); }
By incorporating this method, we ensure that the CSS is applied in all browsers, even those with Internet Explorer's unique loading behavior.
The above is the detailed content of Why Do My Dynamically Loaded CSS Stylesheets Only Work in Some Browsers (and How Can I Fix It)?. For more information, please follow other related articles on the PHP Chinese website!