Lee Tou Lee Tou - 23 days ago 5
Javascript Question

Why am I getting an error when putting self-invoking (IIFE) code into external JS file?

I have written a self-invoking JavaScript code:

(
function assignment12_3(){
// Your code goes in here.
var records = openZipCodeStudyRecordSet();
var zipArray = [];
var zipUnique = [];
while (records.readNextRecord()) {
var zips = records.getSampleZipCode();
zipArray.push(zips);
zipArray.sort();
}
for (var x = 0; x < zipArray.length; x++) {
if (zipArray[x] !== zipArray[x-1]) {
zipUnique.push(zipArray[x]);
}
}
var output = document.getElementById('outputDiv');
for (var y = 0; y < zipUnique.length; y++) {
output.innerHTML += zipUnique[y] + "<br>";
}
}
)();


into my html and it works perfectly, but when I put it into an external JavaScript file, I get an error of:


Uncaught TypeError: Cannot read property 'innerHTML' of null


for my:

output.innerHTML += zipUnique[y] + "<br>";


below is the link to the image with the example of the error and highlighting the line that has the error when I put the code into an external js file.

http://i.imgur.com/RWDbRDT.png

Is it not possible to put self-invoking functions (IIFE) into an external JavaScript file and use it in an html file? Why does my code work perfectly when in an HTML script tag, but not in an external JavaScript file?

Answer

May be you are running your JavaScript code before the your HTML document is loaded so move your all code in the window.onload function and after that run your code:

window.onload=function(){
(
    function assignment12_3(){
        // Your code goes in here.
        var records = openZipCodeStudyRecordSet();
        var zipArray = [];
        var zipUnique = [];
    while (records.readNextRecord()) {
        var zips = records.getSampleZipCode();
        zipArray.push(zips);
        zipArray.sort();
    }
    for (var x = 0; x < zipArray.length; x++) {
        if (zipArray[x] !== zipArray[x-1]) {
            zipUnique.push(zipArray[x]);
        }
    }
    var output = document.getElementById('outputDiv');
    for (var y = 0; y < zipUnique.length; y++) {
        output.innerHTML += zipUnique[y] + "<br>";
    }
    }
)();
}

Let me know what you get after using the above solution.