Do something after an external script is fully loaded via jQuery append

0

I have an external <script> being added to the page via jQuery with:

$("body").append("<scr"+"ipt src='url_do_script.js'></scr"+"ipt>");

This script adds some elements to the page (some tags). The script works perfectly, but it is asynchronous when loading the page, ie the page loads normally without waiting for what the script will return. But I need to manipulate some tags returned by this .js as soon as they are available .

The problem is that I did not find a way to tell when this script was fully loaded on the page with jQuery.

With pure JavaScript I can tell by adding the script via document.createElement and appendChild . Just make a .onload :

var e = document.createElement("script");
e.src = "url_do_script.js";
document.body.appendChild(e);

e.onload = function(){
   // o script foi totalmente carregado
}

How do I do something with .append of jQuery? I've tried other forms like .get , .load and .ajax but it does not work because of CORS (cross-origin resource sharing).

I tried to put a onload="funcao()" into <script> and it also did not work.

Any idea how to do this or is there another way to use jQuery without being .append ?

    
asked by anonymous 05.01.2018 / 01:07

1 answer

1

I was able to resolve the issue with the hint of @Valdeir Psr . Just add the getScript soon after the append that the code recognized that the elements were loaded on the page:

$("body").append('<scr'+'ipt src="url_do_script.js"></scr'+'ipt>');
$.getScript( "url_do_script.js", function() {
   // fazer algo após o script ter sido carregado
});

No CORS error or anything. It worked perfectly.

UPDATE

True that doing a append and using getScript , the script was being called 2 times.

As the <script> tag exists on the page ( <script src="url_do_script.js"></script> ) otherwise it does not work in this specific case, since it still has a id ( <script id="id_qualquer" src="url_do_script.js"></script> ) and is based on that id script works, I circumvented the problem as follows:

$("body").append('<script id="id_qualquer"></scr'+'ipt>');
$("#id_qualquer").attr("src","url_do_script.js");
$.getScript("url_do_script.js")
.done(function(){
   // fazer algo após o script ter sido carregado;
});

I added the src of the script via id and executed in getScript after .done . It worked perfectly.

    
05.01.2018 / 04:00