I think the issue is the value your retriving is not getting it at the correct moment first time round. Thats why on the second postback it would get the correct item value and its loaded within the context properly. have you tried calling the method out of the page load event? so at bottom code just do showStatusAlert();
instead.
or
use this method instead, it loads the list item id on context load
http://hameersaleem.blogspot.co.uk/2012/09/getting-page-field-value-in-custom.html
so would look somthing on the lines of:
<script type="text/javascript">
var pageItem; //variable for list item of page being displayed (which uses this page layout)
var pageFieldNameVar = '_ModerationStatus'; //variable for page field to be retrieved
var context; // This variable will contain SharePoint Client Context
function showStatusAlert(pageFieldName){
//this is the part that you need that you dont have in reloading the page item on first initial load
if (pageItem == null)
setPageContext();
//explicitly requesting to load the field Name for the page item
context.load(pageItem, pageFieldName);
//making the actual request
context.executeQueryAsync(Function.createDelegate(this, function () { onPageFieldSuccess(pageFieldName); }), Function.createDelegate(this, function () { onPageFieldFailed(pageFieldName); }));
}
//sets the pageItem global variable to establish the context for current page
function setPageContext() {
//_spPageContextInfo is defined in every SharePoint page and has pageListId and pageItemId
//properties populated in publishing pages
var pageListId = _spPageContextInfo.pageListId;
var pageItemId = _spPageContextInfo.pageItemId;
var ctx = SP.ClientContext.get_current();
var web = ctx.get_web();
//getting the list item for the current page
var webLists = web.get_lists();
var pageList = webLists.getById(pageListId);
pageItem = pageList.getItemById(pageItemId);
}
//this function is called automatically when request made by getPageField function is successful
function onPageFieldSuccess(pageFieldName) {
//retreiving the page field value from page list item
var fieldVal = pageItem.get_item(pageFieldName);
// 2 - rejected
if(fieldVal == 1){
statusDesc = SP.UI.Status.addStatus("Warning, this page has been rejected, Please view the page history to check for the latest approved version.!");
SP.UI.Status.setStatusPriColor(statusDesc, 'red');
}
}
//this function is called automatically when request made by getPageField function is unsuccessful
function onPageFieldFailed(pageFieldNameVar) {
//do something to display error
}
//calling only getPageField function. This will eventually call other functions eventually rendering the links
_spBodyOnLoadFunctions.push(function(){
ExecuteOrDelayUntilScriptLoaded(showStatusAlert(pageFieldNameVar)
, "sp.js");
})
</script>
</asp:Content>