3

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
Community
  • 1
  • 1
lhk
  • 27,458
  • 30
  • 122
  • 201
  • Are you sure that the event you are trying to listen for hasnt already been fired when including in the index.jade file? – pherris Dec 22 '14 at 17:29
  • Honestly no, I didn't think of that. But why would document.ready fire, if the scripts are not fully loaded ? – lhk Dec 22 '14 at 21:48
  • I thought that maybe how it is loaded from index.jade might be async which would likely move it after the ready event. You could try listening for a resize event and firing it after you are sure the JS is loaded. – pherris Dec 23 '14 at 02:19
  • Interesting idea, I tried your suggestion. That didn't change the problem, the script didn't seem to get events at all. – lhk Dec 23 '14 at 19:28

0 Answers0