Home >Web Front-end >CSS Tutorial >How to Dynamically Load CSS Stylesheets Reliably in Internet Explorer?

How to Dynamically Load CSS Stylesheets Reliably in Internet Explorer?

DDD
DDDOriginal
2024-12-06 02:35:10234browse

How to Dynamically Load CSS Stylesheets Reliably in Internet Explorer?

Dynamically Loading CSS Stylesheet Issues in IE

Attempting to dynamically load a CSS stylesheet using jQuery as follows:

var head = document.getElementsByTagName('head')[0];
$(document.createElement('link'))
    .attr({ type: 'text/css', href: '../../mz/mz.css', rel: 'stylesheet' })
    .appendTo(head);

may encounter problems in Internet Explorer (IE).

Solution:

In IE, reliably adding a new stylesheet after the initial page styles have been loaded necessitates the utilization of the document.createStyleSheet(url) function.

Refer to Microsoft's documentation for further information on createStyleSheet.

Implementation:

url = 'style.css';
if (document.createStyleSheet) {
    document.createStyleSheet(url);
} else {
    $('<link rel="stylesheet" type="text/css" href="' + url + '" />').appendTo('head');
}

The above is the detailed content of How to Dynamically Load CSS Stylesheets Reliably in Internet Explorer?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn