Problems adding script dynamically with Javascript

Asked

Viewed 218 times

1

I’m having trouble at the moment to add a Script dynamically on a page.

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

I am able to add the Script, but I cannot access the object of this Script after this action, the object that is created is the 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 returns is undefined object.

Does anyone have any suggestions ?

  • That file ckeditor.js exports to global space? what is the object you are trying to access and how?

  • @Sergio after the page fully loads exports the CKEDITOR object, but before the page finishes loading I use this code to exbir the objects of Document for( object in window ){ console.log(object); } but the CKEDITOR does not appear at this time, only after.

  • if you do console.log(window.CKEDITOR); within the callback function that Tobymosque suggested, which gives you?

1 answer

2


When you add a script to a page, you should expect it to be loaded before you can use it.

In this way, you should define a function that will be called only after the script load has been completed.

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.
});
  • thank you, the script loads but I can’t access the object generated by the script from the console. After the document is fully loaded the tool loads but at runtime when I try to use the console.log(CKEDITOR). before loading the page I am using the code for( object in window ){console.log(object);} but the CKEDITOR object is not loaded.

  • CKEDITOR is declared within the function?

  • @Rebirth if you do console.log(window.CKEDITOR); within of the callback function that Tobymosque suggested, which gives you?

  • @Sergio, I believe he’s trying to access a variable outside the scope of the function.

Browser other questions tagged

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