Nodejs EJS particles with scripting in the head

I work with EJS for rendering and server-side HTML pages from a Nodejs server. Some partial elements that I include contain scripts and stylesheets that are referenced in the head, but this forces the client to make multiple requests for the same file (for example, if the parent view also includes this file)

For instance:

<!-- file: parent.ejs -->
<html>
    <head>
        <link rel="stylesheet" href="public/mystylesheet.css">
        <script src="public/myscript.js">
    </head>
    <body>
        <%- partial("partial.ejs") %>
    </body>
</html>

And in partial:

<!-- file: partial.ejs -->
<html>
    <head>
        <link rel="stylesheet" href="public/mystylesheet.css">
        <script src="public/myscript.js">
    </head>
    <body>
        This is an EJS partial!
    </body>
</html>

In this case, "mystylesheet.css" is loaded by the client twice (unnecessarily), and it is also "myscript.js"

Is there a simple way (preferably using EJS) to make sure the stylesheet or script is included when it requires a partial, but not if the parent view has already enabled the resource?

+5
source share
1

, EJS , EJS. , script ( - )

, :

//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 -->

,

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

:

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

, , script , - HTML-

, : AJAX,

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

, , AJAX, ( REST, ):

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

, , AJAX, , , , (, )

+2

All Articles