How to load javascript correctly dynamically

Asked

Viewed 972 times

1

I have two pages called header.html and footer.html. They are included on all pages via javascript. For the header to work properly and the menu to open when I pass the mouse I use the bootstrap-Hover-dropdown.min.js script, but this menu only works properly if I include this bootstrap script directly in header.html, but if I do, when loading the index.html page, conflicts appear in the browser console because it loads header and index scripts. If I put to load the bootstrap script on the index page, the menu does not open when passing the mouse.

In summary, the header.html menu does not see this tag that is inserted in index.html:

<script src="assets/global/plugins/bootstrap-hover-dropdown/bootstrap-hover-dropdown.min.js"></script>

And so the menu does not work, but if I put this tag in header.html the menu works, but there appear script conflicts in the browser console.

Any idea how to fix this?

  • Hello @cesarpereira014, your question is a little wide. Please enter more information, preferably the code of your page so we can help you. Take advantage and see on [help] link [Ask].

  • how are you doing header.html and footer include ? using the load function ?

  • Load all the JS at the end of your index, have you tried? I recommend you see how to use the requieJs, it can be useful for you. insert link description here

  • It is through the load yes function

1 answer

0


You can upload your file header.html as you already do in load() and when it is loaded you load your script with getScript, see the example:

$("#resultado").load("header.html", function() {
  // arquivo header.html carregado.
  var boostrapHover = 'assets/global/plugins/bootstrap-hover-dropdown/bootstrap-hover-dropdown.min.js';
  $.getScript(boostrapHover, function(data, textStatus, jqxhr) {
    // arquivo bootstrap-hover-dropdown.js carregado.
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="resultado"></div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.