Problems adding script dynamically with Javascript

1

I'm having trouble dynamically adding a script to a page.

The script I want to add is CKEDITOR (Text Editor).

I am able to add the Script, but I can not access the object of this Script after this action, the object that is created is CKEDITOR .

var script = document.createElement("script");          

script.type = "text/javascript";                        

script.async = true; // Testei  true e false e nada!            

script.src = "objs/ckeditor/ckeditor.js";           

document.getElementsByTagName("head")[0].appendChild(script);

When I try to print the object, the message that it returns is object not defined.

Does anyone have any suggestions?

    
asked by anonymous 09.03.2015 / 13:01

1 answer

2

When you add a script to the page, you should expect it to load before you can use it.

In this way, you should define a function that will be called only after the script loads.

var getScript = function(url, callback)
{
    var head = document.getElementsByTagName('head')[0];
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = url;
    script.onreadystatechange = callback;
    script.onload = callback;
    head.appendChild(script);
}

Then to call add the script, do the following:

getScript('objs/ckeditor/ckeditor.js', function () {
    //aqui o seu script já está carregado, então você já pode acessar as funções e variaveis do mesmo.
});
    
09.03.2015 / 13:14