Sergey Kudryashov Sergey Kudryashov - 9 months ago 48
Javascript Question

Jquery On element load from external script

In my code I have external script that adds some element to my page. This script loads async after document.ready:

<script src=""></script>

This script contains next:

url: '/anyScript',
complete: function(){
alert('yo'); // FIRED
$('body').append('<div id="xxx" />'); // FIRED

I need to wait until this element will appear and add some styles to it


$('body').on('load','#xxx', function(){
width: 100,
height: $('#first_el').height()

This doesn't fire. What to do?


Answer Source

This solution is based on the assumption that you don't have any control over the external script. So the proposed solution is to use an interval based solution to check whether the target element is loaded if so style it and then stop the interval.

In that case, try use $.getScript() to load the script like

jQuery.getScript('', function () {
    var interval = setInterval(function () {
        var $el = $('#xxx');
        if ($el.length) {
                background: 'red',
                width: 100,
                height: $('#first_el').height()
    }, 500);

Demo: Fiddle