user2924127
user2924127

Reputation: 6240

$(window).load in JQUERY is not firing

I have a complicated application where the html and styles are rendered by a framework. I need to get things such as heights, offsets, scrollTop positions, etc from many elements when the page loads. I know

$( document ).ready

Fires before styles are applied to elements hence why I am using window.load instead. The problem is it I can't get it to fire? I have create a fiddle with the new and old way to fire window load, but its not working. In my application I am using jquery 1.11.1, the fiddle uses 1.9.1.

How I am actually calling my code in my application:

<html>
<head>
<script type="javascript" source="https://code.jquery.com/jquery-latest.min.js"/>
</head>
<body>
<H1>
  TITLE
</H1>
<script type="text/javascript">
 $(window).load(function() {
   alert("Window Loaded 1 ");
 });

 $(window).on('load', function() {
   alert("Window Loaded 2 ");
 });
</script>
</body>
</html>

https://jsfiddle.net/9jzLkrve/

Upvotes: 0

Views: 540

Answers (2)

Asons
Asons

Reputation: 87191

3 things goes wrong here

Stack snippet

<script src="https://code.jquery.com/jquery-latest.min.js"></script>

<H1>
  TITLE
</H1>

<script>

 $(window).load(function() {
   alert("Window Loaded 1 ");
 });

 $(window).on('load', function() {
   alert("Window Loaded 2 ");
 });
</script>

Upvotes: 2

charlietfl
charlietfl

Reputation: 171669

The .load() event listener shortcut is deprecated

Use $(window).on('load', function instead. Also keep it outside of $(document).ready() or window.onload

The fiddle automatically puts your code inside onload callback which is why it is not working in your demo. If you change the "Load Type" in fiddle to a "no wrap" the demo works fine

Update based on new html added to question. Your script tag is invalid

Change

<script type="javascript" source="https://code.jquery.com/jquery-latest.min.js"/>

To

<script src="https://code.jquery.com/jquery-latest.min.js"></script>
       <!-- ^ src not source                               ^^ needs closing tag

Upvotes: 3

Related Questions