JavaScript does not take on pages added later

3

I have a problem, which gives me a big question.

I'm developing a website that has a default structure, which makes GET calls in Jquery to fetch new HTML pages for certain parts of the page.

Example: I click on a link and the page change is done without the page reloading.

But there's the problem. Pages added later by Ajax, which have some elements that use code in JavaScript , such as slides, graphs, maps, among other elements, are added correctly, but these elements do not work, only if they are incorporated right at the beginning of the site (as soon as the site is loaded).

What should I do to make sure this does not happen and that these elements work correctly?

    
asked by anonymous 24.03.2016 / 01:06

2 answers

2

I believe you are using the wrong technology for the expected purpose. It is possible to do whatever you want using javascript + jquery, but it is not the best way to do it.

To do the way you are doing I recommend creating new files with just the snippet of code that will change, eg:

index.html

...
<div id="container">
 [aqui_vai_o_conteúdo_carregado]
</div>
...

external.html

<div>
  <h2>Um titulo qualquer</h2>
  <p> Esse é o conteúdo que será carregado dentro do container ao clicar em algum link </p>
</div>

In theory you should only load the required content inside the container instead of reloading all the html, which would be more costly to process. And it is only after this load that you should initialize the plugins. Checking this load with javascript and jquery can be quite annoying, so I recommend frameworks that are suitable for this.

I recommend studying: AngularJS, EmberJS Or if you prefer something lighter and simpler: ReactJS, MithrilJS, RiotJS

All of these frameworks have unique methods for developing single page applications such as binder content, routes, initializers, etc.

    
24.03.2016 / 05:08
1

You can use $ .getScript to load external js. See this example I tested here locally.

What the following is done: $ .get is used to pull the test.html file, and $ .getScript to pull the js corresponding to it.

In test.html has a button with onclick, and the function of this button is in js.js.

base.html

<script src="jquery.js"></script>

<script>
$(function() {

$("#chamada1").click(function() {

$.get("teste.html", function( data ) {
$.getScript("js.js");
$("#conteudo").html(data);
}); 

}); 

});
</script>

<input type="button" value="chamada1" id="chamada1" />

<div id="conteudo"></div>

test.html

<input type="button" value="clique" onclick="alerta1()">

js.js

function alerta1() {
alert("esse é o alerta 1");
}
    
24.03.2016 / 02:18