Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
171
rated 0 times [  177] [ 6]  / answers: 1 / hits: 12063  / 10 Years ago, sun, november 2, 2014, 12:00:00

I was learning Express/Node/Jade and now in the Jade file I want to include a javascript file from the public folder just for the page.
For example, in jade file I type this:


script(src='/javascripts/test.js')

and inside test.js I have a function


function check_test(){
return "It's working!"
}

then I try to call the function in Jade by


- var test_response = check_test()

than I got the error saying that "undefined is not a function" and test.js isn't load at all.
Apparently Jade doesn't load the file, they only transform into HTML code.


I look someone else's question and this is the closest one I can found but it doesn't provide a clear answer of what to do.
In Jade, how can you call a function in an external Javascript


So my question is: In this case what should I do to make it work?


I don't want to load the file in layout.js since I only want test.js only be use by this page.


More From » node.js

 Answers
15

Well... In the first instance, it is different what happens in the browser of what happens on the server. So Jade is a rendering of HTML, therefore if you are in the browser. It's what ExpressJS shipping, ie rendering Jade. If you want to call, your HTML Javascript (Rendering of Jade), should show you where the Javascript. For exmaple



in Server.js



// Get the Javascript in the browser
app.use(/javascripts, express.static(./outJavascripts));
// Get the URL
app.all(/, function(req, res){
// Render the Jade and Send for the client (Browser)
req.render(myTemplate.jade);
});


In myTemplate.jade



script(src='/javascripts/test.js')


In ./outJavascripts/test.js



function check_test(){
console.log(It's working! :D);
return It's working!;
}


If you do this, you will realize that it is run, the file ./outJavascripts/test.js in the browser. And the function check_test never run in the server.


[#41527] Friday, October 31, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
myakylas

Total Points: 66
Total Questions: 85
Total Answers: 95

Location: Guadeloupe
Member since Sat, Aug 22, 2020
4 Years ago
myakylas questions
Thu, Apr 28, 22, 00:00, 2 Years ago
Thu, Apr 8, 21, 00:00, 3 Years ago
Sat, Sep 19, 20, 00:00, 4 Years ago
;