user3549700 user3549700 - 21 days ago 7
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:

<head>
<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="https://code.jquery.com/jquery-3.1.1.min.js"
integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
crossorigin="anonymous"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=<my-key>=initMap"
async defer></script>
<script src="/search.js"></script>
<script src="/create.js"></script>
<script src="/maps.js"></script>

</head>


I also have the following server side code:

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

app.get('/', function(req, res) {
res.sendFile(__dirname+'/index.html');
});

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
*/
});


FIXED:replaced
window.onload = (function(){...});
with
$(document).ready(function(){...});

Answer

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.