Can I run the function after the third party script is loaded?

I want the function to run as quickly as possible, but it has to wait for the other (third party) script to finish loading, otherwise the correct variable will not be defined yet.

Can I listen to a specific script to finish loading and bind a function to this event?

I need some code, so:

When this is loaded:

<script src="https://www.officeball.biz/socket.io/socket.io.js"></script>

      

run this:

function(){ console.log('socket ready!'}`

      

It would seem like I could just mutate the third party script to call the function, but not in this case: socket.io is a dynamically generated script that I have no control over the source.

The alternative would be to wait for the document to load; this question is trying to run the script as soon as possible.

+3


source to share


1 answer


You can create a script and add to your head:

var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://www.officeball.biz/socket.io/socket.io.js';
document.getElementsByTagName('head')[0].appendChild(script);

script.onload = function() { 
    console.log( 'loaded' );
}

      




This example can be wrapped in a function and added to the title of the document:

<script>    
    function load_script( src, callback ) {

        var script = document.createElement('script');
        script.src = src;
        document.getElementsByTagName('head')[0].appendChild(script);

        script.onload = callback;
    }
</script>

      

And it can be used like this:

load_script( 'https://www.officeball.biz/socket.io/socket.io.js', function() {
    console.log( 'socket ready!' );
});

      




Also, as a response to your comment, there is also the option to create a script tag with attributes id

and data

:

<script id="socket-io" data-src="https://www.officeball.biz/socket.io/socket.io.js" type="text/javascript"></script>

      

And to add the attribute src

later, the script will start loading the moment the attribute is set src

:

var script = document.getElementById( 'socket-io' );
script.src = script.getAttribute( "data-src" );

script.onload = function() { 
    console.log( 'socket ready!' );
}

      

And that can of course be wrapped in a function, for example:

<script>    
    function load_script( id, callback ) {

        var script = document.getElementById( id );
        script.src = script.getAttribute( "data-src" );

        script.onload = callback;
    }
</script>

      

And finally:

load_script( 'socket-io', function() {
    console.log( 'socket ready!' );
});

      

+5


source







All Articles