user3549700 user3549700 - 1 year ago 140
Node.js Question

Only one JS script is executed on page load

I have the following html head which loads 3 JS files: search.js, create.js and maps.js:

<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="/maps.css" />
<script src="<my-key>=initMap"
async defer></script>
<script src="/search.js"></script>
<script src="/create.js"></script>
<script src="/maps.js"></script>


I also have the following server side code:

var express =
var path = require('path');
var app = express();
app.use('/', express.static(path.join(__dirname, 'static')))

app.get('/', function(req, res) {

app.listen(3000, function () {
console.log('meetup listening on port 3000!')

when index.html loads, the client seems to only execute one JS script (tested by logging 'script x loaded' in each file). The executed script is always the last one loaded in the head. (i.e. if
<script src="/search.js"></script>
is last then console will only log 'script search.js loaded'). The executed script always works as expected. The other scripts are all loading in the js console, but they do not execute. Any thoughts on what's wrong here?

EDIT: all three scripts look something like

window.onload = (function(){
console.log('search.js loaded');

*event handling and DOM manipulation logic here

window.onload = (function(){...});

Answer Source

It is probably related to how you have set your event handler in your scripts. You can only have one event handlder for 'window.onload" event, the way you have shown. Thus, all the other event handlers for the same event won't be called when scripts are loaded. Try using something like:

window.addEventHandler("onload", function(){
  console.log('I am loaded');

Using the above, you can have multiple event handlers listening for the same event, which in this case is the onload event. I hope this helps.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download