简体   繁体   中英

Script doesn't always fully execute when ajaxed in with jQuery

I've got this clause to execute a script under certain condition;

//if artist page clicked run profile script
if (id == 'artist_link') {
        $.getScript("AJAX/get_profile.js");
}

The problem i'm having is that the script will often not fully execute. Sometimes nothing will be executed other times only parts of it will execute. I can't really provide any more details than this. Strange occurence though is that it always executes fully when firebug is open and I can't find any problems. The browsers that i've tested on and both have this problem are chrome and firefox

jsfiddle with get_profile.js file in.

I could be wrong, but as far as I'm aware, $(location) isn't valid jQuery. Replacing $(location).attr('pathname') with just window.location.pathname would remove a likely error.

A couple of other general things, which shouldn't really affect whether or not it works, but are worth mentioning to improve overall niceness:

  • data returned from a JSON call is an object, not an array. To access the DP element of it for a display picture, you should use data.DP not data['DP'] (same for name , and several other elements
  • .click() is deprecated, use .on() to bind events instead
  • You're looping over an collection ( $.each (data, function(key, val){ ) and inside the loop, are modifying the DOM ( $.append() ) - you'd be better off instead building up a string of HTML during the loop, then add it in a single append after the loop, as DOM insertions are slow for performance
  • You're using the same selector multiple times (see $('#origin') ), which causes jQuery to have to look the element up every time. Either cache it and then call methods on that:
    • $origin = $('#origin');
  • or chain calls to the same element:
    • $('#origin').html('a').append('b').append('c');

I'm almost 100% certain there is a bug somewhere in your get_profile.js file. If it's executing at all, then there isn't any problem with the loading of the file. The problem resides somewhere in your js file and we can't really debug that without seeing the code from it.

Fixed It! I don't know why I wasn't seeing this but the script was being ajaxed in before the page had been ajaxed in resulting in the script becoming unfunctional. Anyway with a bit of fidlling i've fixed it. Thanks for the help!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM