jeff
jeff

Reputation: 1197

time javascript

I have the following problem: on a customer's homepage the navibar is loaded by javascript, but I need to change some URL's on it. If I just start my script on $(document).ready() it runs before the customers script and has no effect. I only can use setTimeout for my function to wait until the other script is ready, but it's not good or safe at all. I can't change anything on the website, only add a javascript - is there a way to time it after the other one?

Upvotes: 0

Views: 138

Answers (4)

iambriansreed
iambriansreed

Reputation: 22241

Fiddle: http://jsfiddle.net/iambriansreed/xSzjA/

JavaScript

var
menu_fix = function(){
    var menu = $('#menu');
    if(menu.length == 0) return;
    clearInterval(menu_fix_int);
    $('a', menu).text('Google Search').attr('href','http://google.com');        
},
menu_fix_int = setInterval(menu_fix, 100);

HTML

<div id="menu"><a href="http://bing.com">Bing Search</a></div>​

Upvotes: 0

Madbreaks
Madbreaks

Reputation: 19539

Yes, add your script at the bottom of the <body /> tag to ensure it does not run until all other scripts have run. This will only work however if your customer is loading the nav links synchronously.

If the nav is being loaded asynchronously, use JS's setInterval to repeatedly check the contents of the nav for links. When you determine the links have been added, cancel your interval check and call your script's logic entry point.

Cheers

Upvotes: 1

CaptainBli
CaptainBli

Reputation: 4201

If you have information about the menu like the id or class, use the onLoad() jQuery method on the element. For example if the code is loading asynchronously, and you add the onload to one of the last elements it should fire after the content has finished.

$.post('AsyncCodeLoad.php', function(data) {
    $('#lastElementToLoad').onLoad(RunMyFunction);
});

Or if you have no chance to insert your code into the async loading just add to the bottom of the </body>:

    $('#lastElementToLoad').onLoad(RunMyFunction);

Just a thought.

Upvotes: 1

djleop
djleop

Reputation: 697

You can use repeated setTimeout, in order to check if menu is accessible.

function check_menu(){
    if(document.getElementById('my_menu')==null){
        setTimeout('check_menu()',500);
    } else {
        //do some stuff
    }
}

Upvotes: 1

Related Questions