Nodejs EJS partials with scripts in the head

元气小坏坏 提交于 2019-12-04 07:25:57

I found a fairly good solution to this problem, which basically boils down to using an EJS variable to keep track of resources included as the EJS document is rendered. Here's a shortened example below, that only works for script tags (but can easily be extended to stylesheets or anything else)

A partial that helps with the inclusion of resources:

//file: "include.ejs"
<% for (var i in scripts) { %> //scripts an arr of js files to (maybe) include
    <% if (!resources[scripts[i]]) { %>
        <script src="<%= scripts[i] %>"></script>
        <% resources[scripts[i]] = true %>
    <% } %>
<% } %> <!-- end for -->

And a file that uses this partial to include scripts

//file: "somepartial.ejs"
<html>
    <head>
        <%- partial("include.ejs", {
                scripts: ["lib/jquery.js", "lib/bootstrap-tabs.js"]
            }) %>
    </head>
    <body>
        <!-- MY EJS PARTIAL! -->
    </body>
</html>

And when rendering the partial:

response.render('somepartial.ejs', {
    resources: {},
    /* some other variables */
});

This way, you can be sure that a script is included by a partial, but not unless it was already included somewhere in the rendered HTML page

A limitation

There is one limitation that I came across: If you load part of your page with an AJAX request like

$("#someDiv").load("/another/part/of/the/page.html");

Then the resources included with the AJAX-loaded portion of the page won't be aware of the scripts already loaded (unless you pass that information in a REST argument, like I'm doing):

$("#someDiv").load("/another/part/of/the/page.html?resources={...}");

Of course, with this little fix, any two parts of the page that are loaded with an AJAX call may request the same resource, and there's no way for them to know that since they are only aware of what the parent document has had loaded (hope that makes sense)

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