Jade: loading external javascript and call functions

I studied Express / Node / Jade and now in the Jade file I want to include the javascript file from the shared folder for the page only. For example, in the jade file I type this:

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

and inside test.js I have a function

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

then I'm trying to call a function in jade on

 - var test_response = check_test() 

than I got an error saying that "undefined is not a function" and test.js does not load at all. Apparently, Jade does not load the file, they only convert to HTML code.

I look at someone else's question, and this is the closest I can find, but it does not give a clear answer about what to do. In Jade, how can you call a function in external Javascript

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

I do not want to load the file in layout.js, since I want test.js to be used only on this page.

+6
source share
3 answers

Well ... In the first case, it is different what happens in the browser of what happens on the server. So, Jade is an HTML rendering, so if you are in a browser. This is what ExpressJS shipping, that is, the rendering of Jade. If you want to call, your HTML-Javascript (Rendering of Jade) should show you where Javascript is located. 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 working! :D"); return "It working!"; } 

If you do this, you will understand that it is running, the file "./outJavascripts/test.js" in the browser. And the function "check_test" never runs on the server.

+3
source

Or put all the folders in a shared folder, e.g. public

public -javascripts -stylesheets -images

and then set this shared folder

app.use(express.static(path.join(__dirname, 'public')));

which means you can

script(src='/javascripts/script.js') link(rel='stylesheet', href='/stylesheets/style.css')

+1
source

Save your JS file and attach it in your Jade file as:

 script(src="filepath/yourJSfile.js") 

Then call the function, I use a button here, for example:

 button(class="btn", onclick='functionName()') 
0
source

Source: https://habr.com/ru/post/977613/


All Articles