Sergey Kudryashov Sergey Kudryashov - 20 days ago 7
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="http://any.com/script.js"></script>


This script contains next:

$.ajax({
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

$(function(){

$('body').on('load','#xxx', function(){
$(this).css({
background:'red',
width: 100,
height: $('#first_el').height()
});
});
});


This doesn't fire. What to do?

UPDATED: http://jsfiddle.net/81ucdoLo/1/

Answer

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('http://any.com/script.js', function () {
    var interval = setInterval(function () {
        var $el = $('#xxx');
        if ($el.length) {
            clearInterval(interval);
            $el.css({
                background: 'red',
                width: 100,
                height: $('#first_el').height()
            });
        }
    }, 500);
})

Demo: Fiddle

Comments