I've got a very basic express setup, with jade as the view engine. The standard template for my views is stored in layout.jade
doctype html
html
head
title= title
link(rel='stylesheet', href='/stylesheets/style.css')
body
block content
script(src='https://code.jquery.com/jquery-2.1.3.min.js')
script(src='/javascripts/global.js')
script(src="/javascripts/local.js")
Then there is an index.jade file
extends layout
block content
h1 Welcome
script(src="/javascripts/local.js")
The idea is that global.js contains global setup that is required by each of my views. Local.js is specific to index.jade.
Both scripts use jquery to hook into document.ready and greet the user like this:
$(document).ready(function(){
alert("hello from global.js"); // or local.js
//...
});
If both scripts are included in the layout.jade file, both alerts are displayed, but the local.js file is only supposed to run in a local file. If local.js is only included in the index.jade file, and not in both, its greeting is not displayed at all.
Apparently the document.ready does not fire from within the second jade file. I can't figure out why. You may register multiple callbacks:jQuery - is it bad to have multiple $(document).ready(function() {});
And in both scenarios the scripts are present in the site source html.
Here is the nodejs console log:
GET /index 304 12.661 ms - -
GET /stylesheets/style.css 304 0.427 ms --
GET /javascripts/local.js 304 0.509 ms - -
GET /javascripts/global.js 304 0.294 ms - -
Why doesn't document.ready fire for the local.js file if it's included in the second jade file ?
UPDATE:
The problem was that the second script was placed in the body of the html document. Apparently that messes up the event routing.
Now layout.jade looks like this:
doctype html
html
head
title= title
link(rel='stylesheet', href='/stylesheets/style.css')
script(src='https://code.jquery.com/jquery-2.1.3.min.js')
script(src='/javascripts/global.js')
block scripts
body
block content
And index.jade like this:
extends layout
block scripts
script(src="/javascripts/local.js")
block content
h1 Welcome