Josh Correia
Josh Correia

Reputation: 4354

jQuery executes before page finishes loading even though I'm using $(window).on('load', function()

I am trying to scrape some times from https://www.speedrun.com/mm for a chrome extension but the issue I'm having is that jQuery loads before the webpage has completed loading. When I refresh the page while having Inspect open it works just fine (I'm assuming it's making the webpage take longer to load) but otherwise I can't scrape the data, it will return blank. Is there any way for me to ensure that the data is ALWAYS loaded first?

$(window).on('load', function() {
    var worldRecord = $('.nobr.center.hidden-xs').text();
    alert(worldRecord);
});

Edit: I tried this as well and got the same result

$(document).ready(function() {
  var worldRecord = $('.nobr.center.hidden-xs').text();
  alert(worldRecord);
});

Upvotes: 1

Views: 74

Answers (5)

Josh Correia
Josh Correia

Reputation: 4354

I found a workaround since loading after the ajax completes doesn't seem to be working. I used the setTimeout function and set it to one second to see if that worked and it did :D

$(document).ready(function() {
    setTimeout(function() {
        var worldRecord = $('.nobr.center.hidden-xs').text();
        alert(worldRecord);
    }, 1000);
});

Upvotes: 0

MSQ
MSQ

Reputation: 479

Please check once if you are getting $ as undefined, Use different instance of JQUERY like

jQuery(document).ready(function() {
  var worldRecord = jQuery('.nobr.center.hidden-xs').text();
  alert(worldRecord);
});

Upvotes: 0

Nikita Puza
Nikita Puza

Reputation: 111

The leaderboard data seems to be loaded using ajax. Have you tried using .ajaxSuccess() or .ajaxComplete() instead of .ready?

Upvotes: 0

Nisal Edu
Nisal Edu

Reputation: 7591

Try this edited with $(document).ready

Load is called when all assets are done loading, including images.But the ready is fired when the DOM is ready for interaction.

Reference

https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onload

http://api.jquery.com/ready/

$(document).ready(function() {
  var worldRecord = $('.nobr.center.hidden-xs').text();
  alert(worldRecord);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

Upvotes: 1

4b0
4b0

Reputation: 22321

Put your code inside document.ready .

$(function() {
   var worldRecord = $('.nobr.center.hidden-xs').text();
   alert(worldRecord);
});

Upvotes: 0

Related Questions