Reputation: 55
I have two HTML documents that both have the same .js script linked just before the /body tag. On the JS document, the top IIFE is linked to an 'id' on one page, and it works fine, but when I go to the second page, the IIFE that is linked to that 'id' won't work. However, when I flip the positions of the IIFEs on the JS doc, the 2nd one (now on top) works and the other one doesn't...
//one
var loop = (function () {
'use strict';
var array = [5, 10, 15, 20],
length = array.length,
levelNumber = 0,
tell = '',
i;
for (i = 0; i < length; i += 1) {
levelNumber = (i + 1);
tell += 'Level ' + levelNumber + ': ';
tell += array[i] + '<br/>';
document.getElementById('loop').innerHTML = tell;
}
}());
//two
var multiple = (function () {
'use strict';
var level = 1,
msg;
switch (level) {
case 1:
msg = 'ONE!';
break;
case 2:
msg = 'TWO!';
break;
}
document.getElementById('test').innerHTML = msg;
}());
Upvotes: 0
Views: 104
Reputation: 150070
If the element doesn't exist on the page then document.getElementById('loop')
will return null
, and trying to do null.innerHTML
will give an error and stop your script from continuing. (If you look in your browser's console you should see the error there.)
Try testing for null
(i.e., testing whether the elements exist), perhaps something like this at the beginning of each function:
var el = document.getElementById('loop');
if (!el) return;
In context:
var loop = (function () {
'use strict';
var el = document.getElementById('loop');
if (!el) return;
var array = [5, 10, 15, 20],
length = array.length,
levelNumber = 0,
tell = '',
i;
for (i = 0; i < length; i += 1) {
levelNumber = (i + 1);
tell += 'Level ' + levelNumber + ': ';
tell += array[i] + '<br/>';
el.innerHTML = tell;
}
}());
//two
var multiple = (function () {
'use strict';
var el = document.getElementById('test');
if (!el) return;
var level = 1,
msg;
switch (level) {
case 1:
msg = 'ONE!';
break;
case 2:
msg = 'TWO!';
break;
}
el.innerHTML = msg;
}());
<p>For this demo, only the "test" element exists, but the second function should work because the first function checks for existence of "loop"...</p>
<div id="test"></div>
Or you could test at the point where you're about to assign the value:
var el = document.getElementById('test');
if (el) {
el.innerHTML = msg;
}
...but given that the functions seem to have no purpose except to update the element there's no point doing the calculations if the element isn't there.
As an aside, your loop
and multiple
variables will both end up with the value undefined
because neither IIFE includes a return
statement.
Upvotes: 1