3

The only related question I found for my issue is this one: page fetched by AJAX cannot execute any javascript

But I don't want do use JQuery. I want to use vanilla javascript.

The problem is that I can't execute any javacript that is inside an html page that is fetched using the fetch api.

Here are my files:

index.html: This is the initial HTML page. It requests a file called index.js as an ES6 module

<!DOCTYPE html>
<html>

<head>
    <script type="module" src="index.js"></script>
</head>

<body>
    <main id="content" role="main"></main>
</body>

</html>

Then I have my index.js file:

import openTemplate from './shared-assets/js/openTemplate.js';

const target = document.getElementById('content');

openTemplate('dashboard.html', target);

This is the openTemplate.js file:

export default function openTemplate(templatePath, targetElement){
    fetch(templatePath).then(response => {
        response.text().then(html => targetElement.innerHTML = html);
    });
}

And finally, the dashboard.html template that refuses to execute javascript:

<h1>Dashboard</h1>
<script type="module">
    import myAlertFunction from 'myAlertFunction.js';

    // this is just a function that encapsulates an alert call
    // my real code will have much more complex functions being imported
    myAlertFunction('test');
</script>

All this code should result in a scenario in which, when my index.html page loads, an alert should display with the text 'test', but this is not happening.

I want this to run on Firefox Quantum >= 66

What am I missing?

  • Heads Up!! `'use strict';` has no meaning in a module. – Keith Apr 23 '19 at 14:19
  • Really? I didn't know that. Can you provide me a link to a documentation? –  Apr 23 '19 at 14:20
  • 2
    found it: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode#Strict_mode_for_modules –  Apr 23 '19 at 14:25
  • Thanks @Keith :D –  Apr 23 '19 at 14:25
  • No problem, this has the relevant bits too -> http://www.ecma-international.org/ecma-262/6.0/#sec-strict-mode-code – Keith Apr 23 '19 at 14:27
  • back to the problem, do you get an errors in the console,. and do you get anything in the network tab?. – Keith Apr 23 '19 at 14:31
  • It does not work like that, you are trying to make available a function in the global scope. From your module watch for an event, is the regular easy way. – NVRM Apr 23 '19 at 14:31
  • @Cryptopat what do you mean? –  Apr 23 '19 at 14:34
  • @Keith no errors in the console. The HTML is loaded, but the javascript is not executed. –  Apr 23 '19 at 14:35
  • Ah, right.. `innerHTML ` does not execute script tags. https://stackoverflow.com/questions/1197575/can-scripts-be-inserted-with-innerhtml – Keith Apr 23 '19 at 14:38
  • you will need to build and append a script element rather than using innerHTML – John Hascall Apr 23 '19 at 14:44

0 Answers0