简体   繁体   中英

self-invoking functions only work embedded in html but not in external javascript file?

I'm hoping someone can help me out here. I'm writing some code that has several self-invoking functions. They all work a treat if I embed them on the html page (see code for one below) but if they (obviously minus the surrounding script tags) are included in my external javascript file instead....no joy, they don't invoke themselves. Any clue as to what might be going wrong if placed in the external file and why they don't invoke (and how to get them to do so!):

The self-invoking functions pulled off the html page:

            <script>

            (function () {
                window.addEventListener("load", function() {
                    var d = new Date();
                    var n = d.toLocaleString();
                    var x = function dateDisplay(){
                    document.getElementById("dateDisplay").textContent = n;
                    }
                  x();    
            })
            document.getElementById("dateDisplay").style.color = "red";
            })();
            var add = (function () {
            var counter = 0;
            return function () {return counter += 1;}
             })();

            function closureCount() {
            var hugeNum = Math.random();
            var fixedNum  = (hugeNum * 100) + 1;
            var randomNum= Math.floor(fixedNum);
            document.getElementById("p_r4").innerHTML = add() + " " + randomNum;   
             //code
            }
            </script>

Try a "less is more" approach:

  1. Make sure <script> and </script> tags have been removed and are not present in the external js file. Script tags are valid in the HTML file only.

  2. Do not attempt to access DOM elements before they are finalized, as in do it in the window load event listener. As per comment the second reference to the date display element needs moving. This could make the two self invoking functions look like:

     (function () { window.addEventListener("load", function() { var d = new Date(); var n = d.toLocaleString(); // access document elements after window load document.getElementById("dateDisplay").textContent = n; document.getElementById("dateDisplay").style.color = "red"; }); })(); var add = (function () { var counter = 0; return function () { return counter += 1; } })(); 

(with '{' and '}' pairs under each other for debugging purposes, change to match your own style.)

I know this is an ancient message in the "Internet-timescale of things moving forward"... but since the question turned out when I was struggling with the same problem in the end of 2018, and there seems to be no accepted answer - or one that actually works, I decided to write a comment for the poor bloke who finds this in 2021 and might not be able to figure it out :)

In short; self executing functions from external files do work ... if the server provides correct MIME-type for the file; "text/javascript" (I'm assuming some of the older MIME-types that have been used for JavaScript-files should work equally well, but I never really tried them). One thing to note, though is that "text/plain" is one of the MIME-types that definitely does not work - and servers that determine the MIME-type based on output of "file"-command (or similar) will try to use that unless configured manually.

So - hope this helps :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM