Skip to content

Commit

Permalink
Defer loading ads until we know if this is some kind of error page (4…
Browse files Browse the repository at this point in the history
…04 or other), to appease Google
  • Loading branch information
dumbmatter committed Nov 21, 2023
1 parent 251f30a commit e8ebb92
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 11 deletions.
2 changes: 1 addition & 1 deletion src/ui/api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import type {
} from "../../common/types";

const initAds = (type: "accountChecked" | "uiRendered") => {
ads.init(type);
ads.setLoadingDone(type);
};

const initGold = () => {
Expand Down
7 changes: 4 additions & 3 deletions src/ui/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -281,9 +281,7 @@ const setupRoutes = () => {
util.ads.trackPageview();
}

if (!initialLoad) {
util.ads.refreshAll();
} else {
if (initialLoad) {
initialLoad = false;
}
}
Expand Down Expand Up @@ -340,6 +338,9 @@ const setupRoutes = () => {
);
const errorPage = genStaticPage("error", "Error", ErrorPage, false);
errorPage(context);
} else {
// No ads on error
util.ads.refreshAll();
}
},
routes,
Expand Down
23 changes: 16 additions & 7 deletions src/ui/util/ads.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,21 +63,27 @@ type AdState = "none" | "gold" | "initializing" | "initialized";
class Ads {
private accountChecked = false;
private uiRendered = false;
private initAfterLoadingDone = false;
skyscraper = new Skyscraper();
private state: AdState = "none";

init(type: "accountChecked" | "uiRendered") {
setLoadingDone(type: "accountChecked" | "uiRendered") {
this[type] = true;
if (this.initAfterLoadingDone) {
this.init();
}
}

private init() {
// Prevent race condition by assuring we run this only after the account has been checked and the UI has been rendered, otherwise (especially when opening a 2nd tab) this was sometimes running before the UI was rendered, which resulted in no ads being displayed
if (this.accountChecked && this.uiRendered) {
if (this.state !== "none") {
// Must have already ran somehow?
return;
}
if (type === "accountChecked") {
this.accountChecked = true;
} else if (type === "uiRendered") {
this.uiRendered = true;
}

if (!this.accountChecked || !this.uiRendered) {
// We got the first pageview, but we're not done loading stuff, so render first ad after we finish loading
this.initAfterLoadingDone = true;
return;
}

Expand Down Expand Up @@ -246,11 +252,14 @@ class Ads {
});
}

// If ads are not yet displayed, this will display them
refreshAll() {
if (this.state === "initialized") {
window.freestar.queue.push(() => {
window.freestar.refreshAllSlots?.();
});
} else if (this.state === "none") {
this.init();
}
}
}
Expand Down

0 comments on commit e8ebb92

Please sign in to comment.