Don't load div that is displayed none in the dom using JS

I have 2 divs, one of them is for Internet explorer and the other for the rest of the browsers. The one which is for IE is hidden using display:none for the other browsers and displayed using media query for Internet explorer. Everything works fine at the moment. But this doesn’t seem like the ideal solution since the display:none div does appear in the DOM which isn’t good for performance. How do I initialize only the elements that are visible or how do I not initialize elements using JS that have display:none

<div style="display:none"id="explorer">Internet explorer</div>
<div id="rest">Chrome,Firefox,etc</div>

@media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
    #explorer{
        display: block !important;
    }
    #rest{
        display: none;
    }
}

So if you load this in Chrome, <div style="display:none"id="explorer">Internet explorer</div> won’t display in the view, but you will be able to see it through the dev tools. I would like this not to initilize at all using JS for chrome, firefox, etc and not initialize <div id="rest">Chrome,Firefox,etc</div> for IE.

5 thoughts on “Don't load div that is displayed none in the dom using JS”

  1. Unfortunately if you write it in the HTML document the normal way, some things are going to happen before CSS or JS get involved. So you would need to have neither div in the document and insert one or the other with JS.

    if (isInternetExplorer) {
        var ieContent = document.createElement(‘div’)
        ...
        document.body.appendChild(ieContent)
    } else {
        var modernContent = document.createElement(‘div’)
        ...
        document.body.appendChild(modernContent)
    
    }
    

    How to get your pages’ contents into JS is the annoying part. One way that lets everything remain in your .html file would be:

    <script type='text/html' id='ieContent'>
        <div>hello internet explorer</div>
    </script>
    
    ieContent.innerHTML = document.getElementById('ieContent').innerText
    

    If possible, it would be better to make your server detect IE and redirect to a whole different .html file; then you have 2 straightforward and well-separated files and no wizardry. And even before then I would question the impact of your invisible div and what you gain by making things more complicated than that.

    Reply

Leave a Comment