1

I have the following code on the head of a html webpage:

<script type="text/javascript" src="Image-Slider.js"></script>
<script type="text/javascript" src="Image-Slider2.js"></script>

On file "Image-Slider.js" I have a bunch of code and then windows.onload = function1; at the bottom.

Image-Slider2.js is the exact same code on a different file. The only difference being which id's on the html page they refer to.

Whichever script is called first works correctly, and the second script (Image-Slider2) doesn't work.

How can I get both scripts to run whenever webpage opens?

Nuthead
  • 29
  • 6
  • Possible duplicate of [Add two functions to window.onload](http://stackoverflow.com/questions/16683176/add-two-functions-to-window-onload) – NineBerry Mar 19 '17 at 00:14

2 Answers2

2

You can't assign multiple event handlers with onload = - assigning a second time overwrites the previous one, for the same reason that x = 3; x = 6 results in x being 6.

You can use .addEventListener() instead:

// in one of your JS files:
window.addEventListener('load', function1)

// in the next JS file:
window.addEventListener('load', function2)

"Image-Slider2.js is the exact same code on a different file. The only difference being which id's on the html page they refer to."

So they are exactly the same except that they're different?

If your code makes use of global variables then repeating it in two files will probably not work because they'll be stepping on each other's toes trying to use the same variables. You can fix that by structuring the code to not use global variables or global functions, for example by encapsulating all of the code in each file in a function like:

// wrapper function
(function() {

  var anyVariableHere;
  function anyFunction() { }

  window.addEventListener("load", anyFunction);

})(); // run the wrapper function immediately
nnnnnn
  • 138,378
  • 23
  • 180
  • 229
  • Thanks. I have got them both to run now and there are conflicts like you said. – Nuthead Mar 19 '17 at 01:07
  • Would I need to have another addEventListener call outside the wrapper function which calls the wrapper function? – Nuthead Mar 19 '17 at 01:08
  • No. Notice that that function has `()` at the end of it - that calls it immediately as per the comment in the code. This is called an "immediately invoked function expression", or IIFE. More details: http://benalman.com/news/2010/11/immediately-invoked-function-expression/ – nnnnnn Mar 19 '17 at 01:20
0

You are probably doing it wrong. Image-Slider sounds like a library. You would only have to include it once and then use another script file to initialize the image slider. If you provide more information on the library you use I can help with more detailed help.

niklas
  • 2,734
  • 3
  • 31
  • 62