1

I'm developing a website using jquery mobile 1.2.0 and jquery 1.7.2, I'm facing an issue trying to execute a js function when the page is loaded.

The normal scenario is that the user loads the page using a link (anchor) so I'm handling the jquery mobile event "pageinit", that works ok, but I need to execute the same code/function when the user access the page using the browser's back button, in that case the "pageinit" event is never fired.

The javascript function modifies the UI so it is needed the UI is loaded before the function gets called.

I'm testing it on Safari 9.1 (iOS 9.3).

My page is very similar to this:

<section id="someid" data-role="page" data-theme="a">
<!-- Page content -->
</section>

<script type="text/javascript">
function myFunction() {
//some code to modify de UI on page loaded
}

$("#someid").on("pageinit", function (e) {
    var page = $(this);

    myFunction();
});
</script>

UPDATE 1:

I've tested all the jquery mobile's events listed here without any luck.

Anon Dev
  • 1,361
  • 3
  • 14
  • 29

2 Answers2

1

Try the pageshow and load events!

From the documentation: The pageshow event is fired when a session history entry is being traversed to. (This includes back/forward as well as initial page-showing after the onload event.)

Also FYI, it looks like pageinit has been depracated in 1.4

$(document).on("pageshow", "#someid", function (e) {
    var page = $(this);

    myFunction();
});
Josh
  • 100
  • 6
  • I've tested this code but do not works on Safari for iOS, the event is not executed after the back button is pressed. – Anon Dev May 03 '16 at 10:24
  • Seems like other people have had this exact thing happen, check out this question: ['pageshow' is not received when pressing “back” button on Safari](http://stackoverflow.com/questions/10106457/pageshow-is-not-received-when-pressing-back-button-on-safari-on-ipad) There's a few solutions, like binding an empty function to `unload` or work with the `persisted` property – Josh May 03 '16 at 15:29
0

Finally I found this SO question that lets me fix the issue, basically it's to use the window event "popstate", here is the exact code I used:

<section id="someid" data-role="page" data-theme="a">
<!-- Page content -->
</section>

<script type="text/javascript">
function myFunction() {
//some code to modify de UI on page loaded
}

$("#someid").on("pageinit", function (e) {
    var page = $(this);

    myFunction();
});

var myCustomEvent = (navigator.userAgent.match('iPhone') != null) ? 'popstate' : 'pageshow';

$(window).on(myCustomEvent, function(e) {
    myFunction();
}
</script>

Note1: The event "pageshow" is perfectly evaluated by most browsers different than Safari Mobile, so it's checking it for those cases.

Note2: I tested this code on Safari Mobile 9.1 (iOS 9.3).

Community
  • 1
  • 1
Anon Dev
  • 1,361
  • 3
  • 14
  • 29