0

There's lots of examples on Stackoverflow on how to detect IE11, but I'm not sure how to use it in a JavaScript conditional statement.

I'm using Tailwind CSS, but it doesn't support IE11 and below. I'd like a way to at least provide some kind of layout via an alternative CSS files.

How would I do something like this with JavaScript?

if (IE11) {
    <link rel="stylesheet" href="/css/ie11.css">
  } else if (IE10) {
     <link rel="stylesheet" href="/css/ie10.css">
  } else if (IE9) {
    <link rel="stylesheet" href="/css/ie9.css">
  } else if (IE8) { {
    <link rel="stylesheet" href="/css/ie8.css">
  } else {
    <link rel="stylesheet" href="/css/tailwind.css">
  }
}

I appreciate global IE11 usage is very low, but I'd like to be able to make use of Tailwind CSS and offer the option of supporting older browsers if needed.

StephenMeehan
  • 1,083
  • 2
  • 15
  • 26
  • 2
    Why are you not satisfied with the question you've linked to? – VLAZ Jan 27 '22 at 16:37
  • I can't see how I'd adapt it, so it works as per my example. – StephenMeehan Jan 27 '22 at 18:47
  • I guess the first thing is that you're mixing HTML code with JS code. You cannot do that. Because they aren't the same thing. You should really focus on one - do you JS? Then [add the stylesheets with JS](https://stackoverflow.com/questions/3922139/add-css-to-head-with-javascript). Do you want to have HTML tags in normal HTML code? Then you should probably [use HTML and CSS only](https://stackoverflow.com/questions/62699032/conditional-html-statements-not-working-as-expected). – VLAZ Jan 27 '22 at 18:57
  • Thanks, I think this might be a better solution. https://getbutterfly.com/switching-from-javascript-to-php-for-browser-detection-and-avoiding-core-web-vitals-penalties/ – StephenMeehan Jan 27 '22 at 19:33

1 Answers1

0

You can use window.document.documentMode to determine if the current browser is IE. Then dynamically import resources into the page.

Simple code:

<script>
        var ieVersion = window.document.documentMode;
        if (ieVersion != 'undefined' & ieVersion > 7 && ieVersion < 12) {
            console.log('Load in IE ' + ieVersion);
            importJsResource(ieVersion);
        } else {
            console.log('Not in IE 8-11..');
            ieVersion = "tailwind";
            importJsResource(ieVersion);
        }

        function importJsResource(version) {
            var fileref = document.createElement("link");
            fileref.rel = "stylesheet";
            fileref.type = "text/css";
            if (ieVersion == 'tailwind') {
                fileref.href = "/Content/tailwind.css";
            } else {
                fileref.href = "/Content/ie" + version + ".css";
            }
            document.getElementsByTagName("head")[0].appendChild(fileref);
        }
    </script>
Xudong Peng
  • 1,463
  • 1
  • 4
  • 9