Jade: load external javascript and call function

落爺英雄遲暮 提交于 2019-11-30 13:46:00

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.

Or put all folders in a common folder, for example public

public -javascripts -stylesheets -images

and then expose that public 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')

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

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

Then call the function, I'm using a button here for example:

button(class="btn", onclick='functionName()')
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!