在ajax成功时替换<title>

I have this code first to get current page slug:

var site_url = document.location.origin;
var slug = href.replace(site_url,'').substring(1).slice(0,-1);

after this I am using function to capitalize slug before put to

function CapitalFirstLetter(string)
{
    return string.charAt(0).toUpperCase() + string.slice(1);
}

var page_title = CapitalFirstLetter(slug);

And finally I am trying get it works on ajax success here:

$.ajax({
    url: href,
    success: function(data) {
       // update the page title
       document.title = page_title;
    }
});

But nothing happens


Some solution I have for now

I make it works finally, since I am loading pages by ajax, I decided change title not on ajax success, but inside each page add script like this

$(function() {
    var loc = document.location.href;
    var site_url = document.location.origin;
    var slug = loc.replace(site_url,'').substring(1).slice(0,-1);
    var page_title = CapitalFirstLetter(slug);
    document.title = page_title;
});

works perfect now, but I am not sure if this good solution?

$.ajax({
    url: href,
    success: function(data) {
       // update the page title
   $("title").text(page_title);
    }
});

reference text()

I Think the problem is that your ajax call is completed before the page_title-variable is set, see this fiddle as a demo.

You can fix it for example delaying the ajax call with

setTimeout(function() {
    $.ajax({
      url: href,
      success: function(data) {
      // update the page title
       document.title = page_title;
      }
   });
}, 100);

Or using the ajax-functions beforesend to generate the title:

var page_title;

$.ajax({
      url: href,
      beforeSend: function() {
         page_title = ...  // generate the title...
      },
      success: function(data) {
      // update the page title
       document.title = page_title;
      }
   });