Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading scripts dynamically

I'm loading a few YUI scripts dynamically in my code in response to an Ajax request. The DOM and the page is fully loaded when the request is made - it's a response for an user event.

I add the <scripts> tag to head as children, but I stumbled in a few problems:

I add two YUI scripts hosted at the Yahoo! CDN and an inlined script of my own responsible for creating object, adding event listeners and rendering the YUI widgets. But I when my script run the YUI scripts are not loaded yet giving me errors and not running as I expect.

There's a way to only run my script (or define a function to be run) when YUI scripts are fully loaded?

like image 211
Vitor Py Avatar asked Jun 26 '10 23:06

Vitor Py


People also ask

How do I load a dynamic script In react?

If we don't find an existingScript ; we create the script dynamically. We start by creating an empty <script></script> tag in the memory as script and then assign the necessary attributes to its src and the id to identify the script later. Finally, we append the script to our <body></body> tag to actually load this.

Are script tags loaded synchronously?

A/B testing scripts can be loaded in two ways: Synchronously, where scripts are loaded sequentially, one after another, starting with the <head> tag. Asynchronously, where some scripts can be loaded simultaneously.


2 Answers

Have you tried an onload event?

Edited:(thanks Jamie)

var script = document.createElement("script");
script.type = "text/javascript";
script.src = src;
//IE:
if(window.attachEvent && document.all) {
    script.onreadystatechange = function () {
        if(this.readyState === "complete") {
            callback_function(); //execute
        }
    };
}
//other browsers:
else {
    script.onload = callback_function; //execute
}
document.getElementsByTagName("head")[0].appendChild(script);
like image 86
tcooc Avatar answered Sep 20 '22 12:09

tcooc


If you're using YUI 2.x I highly recommend using the YUI Get utility, as it's designed to handle just this sort of a problem.

like image 24
Tivac Avatar answered Sep 19 '22 12:09

Tivac