Help : bootstrap modal and w3-include, a love story not meant to be?

Hello everyone,
I’ve been having trouble with this code.
There is another modal in content.html, and I would like a script to be triggered when I close any of the modals. It overall seems to be working, it works from the start with “modal2” but to get it working on the included one I have to refresh the page once.
Is there a discrepancy caused by w3-include that makes it not work from the start?

    <div w3-include-html="content.html"></div>
    <script src="assets/content.js"></script><script>includeHTML();</script>

<!-- INFO RDV -->
<div class="modal fade" id="modal2" tabindex="-1" role="dialog" aria-labelledby="modalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="modalLabel">Modal2</h5>
      <div class="modal-body">

    <p>lorem ipsum dolor sit amet</p>


    <script src="" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <script src="" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
    <script src="" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>

    <script type="text/javascript">
    $(".modal").on('', function () {
      alert('script working');

First, it’s important to note that there’s no magic behind the w3-include-html attribute. Best I can tell from a google search is that it originates from W3Schools and doesn’t appear to be a part of any standard. You could rename this attribute to whatever you like in both the HTML and content.js and it would work the same.

For the reason your code isn’t working, here’s the order things happen when your page loads:

  • content.js is loaded
  • includeHTML() requests content from content.html asynchronously
  • script tag at the bottom of the page is executed and adds hide event handler to modals
  • includeHTML() finishes loading content and adds it to the page

Because the event handlers are added before includeHTML() has added content to the page, any modals in the included content won’t have the event handlers attached. Without testing, I would imagine that it works after refreshing the page because the content is cached by this point and so gets added to the page in time to receive the event handler.

I don’t much like this approach for loading content, but to make it work I’d probably modify includeHTML() to take a callback function to call once it has finished loading.

based on your answer i figured it was indeed a loading time issue so i embedded my script in a $( document ).ready() function and… it works!!! maybe it’s a patch that will soon need patching but it solves my problem for now. thank you!