Does hidden javascript still run?

I was curious if javascript was still executed by the browser even if it was within an element that is hidden in the DOM. A quick search yielded no conclusive evidence, so I decided to test myself.

Quick answer: Yes, it does still execute – for both inline and included javascript regardless of how it’s hidden (display:none or visibility:hidden).

I made a simple test script to see if scripts still run if hidden. Then I tested it on: Internet Explorer 7, 8, 9, Chrome, Safari, and Firefox and all work the same way.

Here’s the test script I used. Within each browser, I got 7 popup windows. In case you’re wondering. I wanted to test to see if including a javascript made any difference, so the ‘testjs.js’ script just makes a simple alert call.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
                <script>
                alert('head');
                </script>
</head>
<body>
                <div>
                                visible div
                                <script>alert('visible div');</script>
                </div>
                <div style="display:none">
                                display:none
                                <script>alert('displaynone div');</script>
                </div>
                <div style="visibility:hidden">
                                visibility:hidden
                                <script>alert('invisible div');</script>
                </div>
               
               
                <div>
                                visible div
                                <script src="testjs.js"></script>
                </div>
                <div style="display:none">
                                display:none
                                <script src="testjs.js"></script>
                </div>
                <div style="visibility:hidden">
                                visibility:hidden
                                <script src="testjs.js"></script>
                </div>
 
</body>
</html>

Posted

in

,

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *