0

I am trying to understand why my script tag is not being executed with EJS. I am using Express JS and EJS template engine. I am sending to front end a compiled EJS partial template:

router.get("/piechart/", async (req, res, next) => {
  try {
    const ejsPartialFile = await readFileAsync(
      "./piechart-title.ejs",
      { encoding: "utf-8" }
    );
    const data = {title: "something important"}
    let ejsFunction = ejs.compile(ejsPartialFile, { client: true });
    res.status(200).send(ejsFunction ({ data }));
  } catch (e) {
    console.error(e);
    next(e);
  }
});

Which also contains tag with javascript file:

<div class="form-group">
      <label>Edit Piechart title</label>
      <input
        type="text"
        class="form-control"
        name="piechart-title"
        value="<%= data.title %>"
        maxlength="10"
      />
    </div>

<script src="/javascripts/testing.js"></script>

The javascript just contains some random stuff which should be executed when it is read:

(function() {
  console.log("testing if javascript file is being read");
})();

However, what happens is that the html gets added with correct things, to the page, however, the javascript doesnt get executed and I get no error. I guess something blocks it? Maybe someone has an idea?

Regards, Rokas

UPDATE

I attach javascript which is used to attach the html:

if (response.status === 200) {
    const data = await response.text();

    const element = document.getElementById("edit-fields");
    onePagerEditField.innerHTML = data;

  }

r.Die
  • 125
  • 3
  • 14
  • Open the Network tab in the browser's developer tools. Is the JS file requested? Does the response contain what you expect? – Quentin Feb 18 '20 at 13:38
  • It contains the html together with the script tag in response, however, the javascript file was not downloaded – r.Die Feb 18 '20 at 14:46
  • The Network tab shows that the request for `/javascripts/testing.js` returns the HTML document?! – Quentin Feb 18 '20 at 14:49
  • No, I mean the first request returns the compiled EJS templated to HTML with script tag. The second request in network tab doesn't launch (which should download /javascripts/testing.js) – r.Die Feb 18 '20 at 14:54
  • There's no obvious reason for that (unless you have the Network tab filtering to show only documents), the code looks fine. Try passing the HTML through [a validator](https://validator.nu/). – Quentin Feb 18 '20 at 14:55
  • Well html works, it just that the script tag doesnt start. Somehow I guess this has to do that this script tag is inserted via insertHTML. But I cannot find explanation for this. – r.Die Feb 18 '20 at 15:06
  • "Somehow I guess this has to do that this script tag is inserted via insertHTML." — It is?! That's a pretty major thing to omit from a [mcve] – Quentin Feb 18 '20 at 15:08
  • Yes, that's true I just added the update, which I thought could be related. – r.Die Feb 18 '20 at 15:12

0 Answers0