没有不值得去解决的问题,也没有不值得去学习的技术!

From Blank Source to AdSense Saturation: Production Wrap-Up for A Tour of Go Option B

Figure 2: In Plan B's production environment, the source code was normal, but the course body height was abnormally shortened, and the footer entered the first screen prematurely.

作者:

在

In the previous articles, I documented several major decisions made during this round of ad optimization for A Tour of Go.

Initially, despite the obvious large visual blank spaces on the course pages, standard Google AdSense display ads simply would not appear.

Subsequently, we went through the following stages:

  • Whether to abandon the SPA for AdSense;
  • The final decision to retain the original SPA architecture of A Tour of Go;
  • Although AdSense Preview found a candidate ad slot below the footer, this position did not fit the actual course experience;
  • Adding explicit manual course ad slots;
  • Plan A used MutationObserver to listen for page DOM changes and manage SPA ads;
  • Plan A worked, but the implementation gradually became complex and developed some low-probability, hard-to-reproduce issues;
  • Finally switching to Plan B, letting ads directly follow the lifecycle of the Angular course view;
  • To resolve a long-standing SPA SEO issue, generating Prerender HTML for 103 official course pages simultaneously.

At this point, the major architectural direction was largely set.

However, after deploying Plan B, Prerender, Angular, CodeMirror, and real AdSense together into the production environment, several new rounds of issues emerged consecutively.

This article primarily documents:

How Plan B finally stabilized after entering actual production.

First, clarify the timeline

There were quite a few issues in this round, and without distinguishing the phases first, it is easy to conflate symptoms caused by different reasons.

The actual process was roughly as follows:

Plaintext
Plan A
MutationObserver manages SPA ads
        ↓
Implementation complexity increases
        ↓
A few hard-to-reproduce issues appear
        ↓
Switch to Plan B

Plan B
Angular course view manages ad lifecycle
        ↓
Add 103-page Prerender
        ↓
Handle the Prerender → Angular → CodeMirror handoff
        ↓
Initial source code still has a very brief blank, but acceptable
        ↓
Continue testing in production
        ↓
Discover real AdSense modifies course ancestor node heights
        ↓
Footer pulled into the first screen
        ↓
Review historical Plan A
        ↓
Discover Plan A actually had a valid piece of layout protection
        ↓
Only bring this capability back to Plan B
        ↓
Final production verification complete

With this context, the subsequent issues become much easier to understand.

Why Plan A was ultimately abandoned

After deciding to keep the SPA, the first ad implementation to actually go live was Plan A.

The core idea of Plan A was to use:

Plaintext
MutationObserver

to observe the page DOM.

The general flow was similar to:

Plaintext
Listen for page changes
        ↓
Determine current course state
        ↓
Find ad slot
        ↓
Clean up old ad
        ↓
Create new ad
        ↓
Continue listening for page changes

This approach had one obvious advantage:

It did not require major modifications to the original Angular routing of A Tour of Go.

As long as the page DOM eventually changed, the external ad logic had a chance to respond.

Plan A did work successfully; it was not just a concept that existed only in the discussion phase.

After clicking “Next” in the SPA, it could also reprocess the ads.

The real problem was:

As the implementation was continuously supplemented, it became increasingly complex.

The A Tour of Go page itself generates a massive amount of DOM changes:

  • Angular route switching;
  • CodeMirror initialization;
  • Editor updates;
  • Course catalog changes;
  • Playground execution results;
  • Creation and destruction of various dynamic elements.

If the ad logic relied on observing these DOM changes to infer:

Has the user now entered another lesson?

it required constantly adding new condition checks and protection logic.

Later, during testing, we encountered some low-probability issues, such as:

  • Example source code occasionally being empty;
  • “Next” occasionally appearing not to respond properly.

The most troublesome part was not these issues themselves, but rather:

They were very hard to reproduce reliably.

They might be fine after a refresh.

They might also be fine after re-entering the page.

Flipping through many pages consecutively might not trigger them again.

Therefore, at the time, we could only speculate:

The problem was likely related to the increasingly complex DOM observation, node handling, and execution timing in Plan A.

But because they could not be reliably reproduced, it was also difficult to precisely attribute each symptom to a specific observer callback.

At this point, the return on investment for patching Plan A was diminishing.

So the decision was made:

Instead of having the ad logic infer from the outside of the DOM what Angular was doing, directly use the course lifecycle explicitly provided by Angular.

This was Plan B.

Plan B shrinks the ad lifecycle to the current course

The core of Plan B is much simpler than Plan A.

Current course view created:

Plaintext
mount()

Current course view destroyed:

Plaintext
$destroy
↓
unmount()

That is:

Plaintext
Angular course view
        │
        ├── Create
        │    └── mount ad
        │
        └── Destroy
             └── unmount ad

When the user goes from:

Plaintext
/tour/basics/1

to:

Plaintext
/tour/basics/2

there is no longer a need for a global observer to guess:

To what extent must the DOM change to be considered a true page switch?

Angular itself already knows when the old view is destroyed and the new view is created.

The ads can simply follow this lifecycle.

Therefore, the goal of Plan B was not to add more protection logic, but rather the opposite:

To reduce the ad code’s understanding of and intervention with the entire Tour DOM.

After switching to Plan B, the occasional “Next button unclickable” issue from Plan A did not reappear.

Then, 103 pages of Prerender were added

Once Plan B was finalized, another long-standing issue entered the official resolution phase:

SPA SEO.

Google Search Console had previously flagged multiple different course URLs as duplicate pages.

Thus, the final decision was:

Plaintext
103 official course URLs
        ↓
103 independent Prerender HTMLs

Each course URL would directly include the following in the initial HTTP response:

  • Current page title;
  • description;
  • canonical;
  • Course body text;
  • Example source code.

This resolved the server’s initial response and page identity issues.

But it also introduced a new browser-side issue:

Just because the Prerender HTML already contained the source code did not mean the Angular and CodeMirror takeover process was entirely free of visual changes.

After Plan B + Prerender, the initial source code was still briefly blank

While testing at this stage, a rather typical phenomenon could be observed.

The course body text on the left side of the page had already appeared.

The right side had also entered the current example file.

However, the code area would briefly remain blank.

Figure 1: After adding Prerender and adopting Plan B, a brief blank example source code appeared when first opening the course page.
Figure 1: After adding Prerender and adopting Plan B, a brief blank example source code appeared when first opening the course page.

An important distinction must be made:

This source code blank was not the hard-to-reproduce intermittent bug from Plan A.

Plan A had already been replaced.

The issue at this stage came from the new rendering chain:

Plaintext
Server Prerender
        ↓
Browser displays initial DOM
        ↓
Angular bootstrap
        ↓
Route takeover
        ↓
CodeMirror initialization
        ↓
Final editor state

In other words, the server had already provided the source code, but the normal browser still had to go through the Angular and CodeMirror takeover.

What truly needed optimization was this handoff process.

Prerender, Angular, and CodeMirror need a stable handoff

Several adjustments were made around this issue subsequently.

Prerender directly saves the source code in the official textarea

No additional hidden source carrier is maintained.

The current page’s default example file goes directly into the textarea originally intended for the editor.

This way:

Plaintext
Prerender source

and:

Plaintext
Editor initial source

maintain the same source as much as possible.

Angular route takes over only after course data is ready

This avoids creating the editor view first and then waiting for lesson data to fill in.

The flow is consolidated as much as possible into:

Plaintext
Lesson data ready
        ↓
Enter editor route

rather than exposing the intermediate empty state to the user.

footer moved out of the route-owned partial

The footer originally followed the course route DOM.

This meant that when Angular replaced the current course view, the footer would be destroyed and recreated along with it.

Subsequently, the footer was moved to the stable page shell:

Plaintext
Stable shell
├── header
├── Angular course view
└── footer

This way, the SPA’s next page only replaces the course area, and the footer no longer participates in the route lifecycle.

The very brief initial source code blank was ultimately accepted

After these adjustments, page stability had improved significantly.

When subsequently clicking “Next” in the SPA, the source code could basically appear quickly.

However, when directly opening a course URL for the first time, a very brief code blank process could still be seen.

This was not optimized further indefinitely.

The reason was that continuing to pursue absolutely zero hydration visual changes would likely require further expanding the modifications to the Angular, CodeMirror, and Prerender workflows.

And the actual experience had already become:

Plaintext
First open
May have a very brief source code blank
        ↓
Page completes takeover
        ↓
Subsequent SPA pagination is fast

Compared to continually increasing architectural complexity, I ultimately accepted this minor visual trade-off.

This was also a rather important boundary in this round:

Not every detail that can be further optimized is worth increasing long-term maintenance costs for.

Also added deterministic testing for Prerender

Prerender had another engineering issue:

Was the HTML generated each time for the same course URL completely identical?

If Chrome produced different DOMs for each Prerender:

  • The release SHA would change;
  • Git diff or build diff would produce noise;
  • It would be hard to tell whether the page had actually changed content or if the browser’s rendering result was unstable.

So later, a full browser regression was added.

For the same official page:

Plaintext
/tour/basics/1

using two independent:

  • output root;
  • Chrome profile;

to complete the Prerender separately.

The final requirement for the two HTMLs was:

Plaintext
bytes.Equal

It also checked:

  • The final Prerender HTML contained no .CodeMirror runtime DOM;
  • The textarea content had to equal the current route.Files[0];
  • There were no extra hidden source carriers.

Only then did Prerender truly become a repeatable, verifiable official build action.

After the page was basically stable, new issues appeared in production

At this point, the integration of Prerender and Plan B was basically complete.

The source code could display normally.

SPA pagination to the next page also worked.

But after continuing to test in the real production environment, another anomaly occurred.

This time, the source code was completely fine.

The problem became:

The footer was pulled into the first screen prematurely.

Figure 2: In Plan B's production environment, the source code was normal, but the course body height was abnormally shortened, and the footer entered the first screen prematurely.
Figure 2: In Plan B’s production environment, the source code was normal, but the course body height was abnormally shortened, and the footer entered the first screen prematurely.

From the screenshot, it can be seen that:

  • The left course body text is normal;
  • The right example source code is normal;
  • CodeMirror has finished initializing;
  • But the footer appears at a very high position;
  • And below the footer there is a large, completely meaningless blank space.

This was clearly not the previous Prerender hydration issue.

What had actually changed was:

The course body height.

Stranger still, the results differed across browser environments

There was a very crucial clue to this issue at the time.

In a normal browser:

Anomaly.

After switching to an incognito window:

The final layout was basically normal.

Same code, same course page, yet different layouts appeared due to different browser environments.

This started pointing towards:

Third-party scripts.

And one of the most important third-party scripts on the current course page was naturally AdSense.

Finally caught the real inline style pollution

After continuing to inspect the actual styles of several core course layout nodes, clear evidence was finally found.

At the time, #editor-container was written with:

Plaintext
height: auto !important;
min-height: 0px !important;

#left-side also showed:

Plaintext
height: auto !important;
min-height: 0px !important;

Two layers of .relative-content also had the same override.

The course ad container itself showed:

Plaintext
height: auto !important;

The actual page geometry data measured at the time was roughly:

Plaintext
viewportHeight = 963
footerTop      = 418.5

That is:

The browser viewport height was close to:

Plaintext
963px

But the footer top had already moved to:

Plaintext
418.5px

The course body should have maintained a height of at least roughly one full viewport.

Now it was compressed to just over four hundred pixels.

This explained why the footer suddenly entered the first screen.

!important makes it hard for normal CSS to reliably override

If the third party only added:

CSS
height: auto;

there would still be many ways to override it with our own stylesheet.

The problem was that what was actually seen was:

CSS
height: auto !important;
min-height: 0px !important;

This directly broke through the original height constraints.

What was more troublesome was:

The third-party script could write it again later.

So even if it was manually cleaned up once:

Plaintext
height:auto!important

it did not mean the problem was completely resolved.

What was truly needed was:

When this specific pollution reappeared, the page could recover in time.

Only then was the historical implementation of Plan A reviewed

After continuing to dig through the Git history, a very crucial fact was discovered.

Plan A had actually already encountered the issue of AdSense modifying page heights.

So in Plan A, besides:

Plaintext
Global MutationObserver
→ Infer SPA page changes
→ Manage ad lifecycle

there was also another block of logic:

Plaintext
layout protection

It was specifically responsible for checking several key layout ancestor nodes.

If it found:

Plaintext
height: auto !important

or:

Plaintext
min-height: 0px !important

it would remove these two specific anomalous properties.

At the same time, it listened for subsequent style changes on these nodes to prevent AdSense from writing them again.

This raised a very interesting question.

When switching from Plan A to Plan B, the deletion was too thorough

The biggest problem with Plan A was that the implementation was too complex.

The part that most needed to be removed was:

Plaintext
Listen to entire page DOM
        ↓
Infer SPA route
        ↓
Manage ad lifecycle

So removing the global DOM observer when switching to Plan B was the right direction.

But at the time, it also incidentally removed from Plan A:

Plaintext
AdSense layout protection

Later, the production environment proved:

Although both blocks of logic used MutationObserver, they were actually solving completely different problems.

The first type of observer:

Inferring SPA state from overall DOM changes.

This type had high complexity and was ultimately replaced by Plan B’s Angular lifecycle.

The second type of observer:

Only observing a few specific layout nodes, and only handling two already-confirmed anomalous styles.

This type was actually a very narrow defense mechanism.

The problem was not:

Whether there was a MutationObserver or not.

But rather:

What the Observer was actually observing, why it was observing, and where its lifecycle boundaries lay.

Ultimately, Plan A was not restored

After finding Plan A’s historical code, the entirety of Plan A was not restored.

Because in terms of ad lifecycle, Plan B was already much clearer.

What was ultimately adopted was:

Retaining Plan B, and only bringing back the layout protection from Plan A that had already been verified in the production environment.

Thus, the final structure became:

Plaintext
Angular course view
        │
        ├── mount()
        │      ├── Create current course ad
        │      └── Establish layout protection for current view
        │
        └── $destroy
               ├── unmount ad
               └── disconnect layout protection

The SPA ad lifecycle was still determined by Angular.

The MutationObserver was no longer responsible for determining whether the SPA switched pages.

It was only responsible for a very limited task:

Preventing real AdSense from rewriting the two height properties that were confirmed to break the course layout.

layout protection only guards four specific nodes

The new implementation did not restore the global:

Plaintext
document.body MutationObserver

Instead, it only found a few specific ancestors of the editor where the current course ad resided:

Plaintext
#editor-container
.relative-content
#left-side
.relative-content

The observation scope was not expanded beyond this.

And it would not:

JavaScript
element.removeAttribute("style")

crudely delete the entire style like this.

It only handled two precise conditions.

If:

Plaintext
height == auto
and priority == important

then it would delete height.

If:

Plaintext
min-height == 0px
and priority == important

then it would delete min-height.

All other inline styles were preserved.

This avoided as much as possible:

Accidentally damaging the normal styles of third parties or the Tour itself while trying to resolve a side effect of AdSense.

The observer must also be destroyed with the course view

After reintroducing the local MutationObserver, there was another issue that had to be strictly controlled:

The observer could not be allowed to accumulate continuously as the SPA paginated.

Therefore, just like the ad itself, it belonged to the current course mount.

Page 1:

Plaintext
mount
↓
observer #1

Click next page:

Plaintext
$destroy
↓
disconnect observer #1

Page 2:

Plaintext
mount
↓
observer #2

It could not end up with:

Plaintext
observer #1
observer #2
observer #3
observer #4
...

This was the kind of complex state the old plan was most likely to devolve into again.

This time, intermittent issues had to be turned into automated tests

A very direct lesson Plan A gave me was:

“Not reproducing it after many consecutive manual tests” does not prove that this type of issue does not exist.

Because these issues often involve:

  • SPA view lifecycle;
  • DOM mutation;
  • observer;
  • CodeMirror;
  • Third-party scripts;
  • Browser runtime timing.

Therefore, two sets of real browser regression tests were specifically added in the end.

Figure 3: Both browser regression tests for Plan B SPA lifecycle and AdSense layout protection passed.
Figure 3: Both browser regression tests for Plan B SPA lifecycle and AdSense layout protection passed.

The first test:

Plaintext
TestCourseAdSPALifecycleInBrowser

Verifies Plan B itself:

  • Current course creates ad;
  • SPA next page creates a new ad lifecycle;
  • Old ad cleaned up correctly;
  • Multiple navigations do not cause node accumulation;
  • Ad anomalies do not interrupt normal navigation.

The second test:

Plaintext
TestCourseAdLayoutProtectionInBrowser

Verifies the newly reintegrated local layout protection:

  • The first height pollution write can be cleaned up;
  • A second write can still be cleaned up;
  • After SPA switch, the old observer is invalidated;
  • The new view observer works normally;
  • Multiple SPA navigations do not accumulate protection instances;
  • The footer still remains after the course body.

Final result:

Plaintext
PASS

This way, if the course ad related code is modified again in the future, there is no need to wait for a random footer anomaly in production to know a regression has occurred.

After automated tests pass, real Google ads must still be checked

However, after the browser tests passed, I still did not immediately consider this round of work complete.

Because what caused the issue was:

Real AdSense.

Automated tests could only simulate:

Plaintext
Writing the same anomalous inline style to the node
↓
Verifying if layout protection can recover

They could not prove that:

Plaintext
Real Google ads
+
Angular
+
CodeMirror
+
Prerender
+
SPA navigation

would definitely work normally when running together.

So testing still needed to continue in production.

Initially, real requests frequently returned unfilled

After the new code was deployed, the course layout had returned to normal.

The footer no longer entered the first screen.

However, the manual ads often did not display.

Continuing to inspect the ad nodes showed:

Plaintext
data-ad-status="unfilled"

Along with:

Plaintext
data-adsbygoogle-status="done"

This indicated:

The ad request had been processed.

It was just that Google did not return an actual ad this time.

Further inspection of the network requests also confirmed:

Plaintext
slotname=4728596962

and parameters like:

Plaintext
format=847x280

as actual request parameters.

Moreover, after moving from one SPA course to the next page, the current URL in the request also changed to the new course address.

So this actually proved:

Plan B’s fresh request was working properly.

The entire chain was:

Plaintext
New course view
        ↓
New ins.adsbygoogle
        ↓
New Google request
        ↓
Google returns unfilled

rather than:

Plaintext
SPA next page
↓
No new ad request at all

These two situations must be distinguished.

Finally, a real ad was successfully displayed

After continued testing, Google eventually returned a real display ad.

Figure 4: Plan B ultimately successfully displayed a Google ad in the real production environment, while source code, SPA, and footer layout were all normal.
Figure 4: Plan B ultimately successfully displayed a Google ad in the real production environment, while source code, SPA, and footer layout were all normal.

This screenshot basically serves as the final acceptance for the entire round of optimization.

It simultaneously proved several things.

The manual course ad slot actually works for real

This was not:

  • AdSense Preview;
  • A self-written placeholder;
  • A test iframe.

But a real Google ad had been displayed.

Plan B did not block AdSense

The consecutive unfilled appearances earlier were not because Plan B could not load ads.

The real filled ultimately proved the ad chain was complete.

layout protection did not damage the ads either

The new protection logic only cleaned up two very specific height pollution values in a few ancestor nodes.

It did not break:

  • The ad iframe;
  • The ad request;
  • The ad size;
  • Normal display.

The footer ultimately remained normal

After the real ad appeared:

Plaintext
Course body text
Normal

Example source code
Normal

Ad
Normal

Page height
Normal

Footer
Normal

This was the state that truly needed to be achieved.

Ad size and fill rate will not be adjusted further for now

The successfully displayed ad was noticeably wider than the small square ads frequently seen the day before.

At the time, it had actually requested an ad size of:

Plaintext
847x280

At the same time, there were quite a few:

Plaintext
unfilled

encountered that day.

So a new question naturally arose:

Would a wider ad size lead to a drop in the actual fill rate?

This has not been adjusted further for now.

Because a lot of:

  • Refreshing;
  • Hard refreshing;
  • Consecutive SPA pagination;
  • Ad request testing.

had already been done for acceptance that day.

None of these were natural user traffic.

Coupled with the fact that the current site traffic and ad display samples were still small, it was easy to misjudge based solely on this round of testing.

So the current decision is:

To keep the existing ad size unchanged for now.

After accumulating a few days of natural visits, we will then combine:

  • Coverage;
  • Ad requests;
  • Impressions;
  • Actual display size;

to determine whether it is necessary to reduce the desktop ad width again.

This item no longer blocks the official wrap-up of the current ad implementation.

Ultimately, the complex DOM management plan was not restored

In retrospect, the most important change from Plan A to Plan B was not:

Changing from MutationObserver to not using MutationObserver.

Because in the final Plan B, a very narrow-scoped observer still existed.

What really changed was:

The responsibility boundaries.

Plan A:

Plaintext
Globally observe DOM
↓
Understand what the entire SPA is doing
↓
Manage ads
↓
Handle various page side effects simultaneously

As features were added, the implementation became increasingly complex, and hard-to-reproduce issues emerged.

Final Plan B:

Plaintext
Angular
Responsible for course lifecycle

course ad helper
Responsible for creating / destroying ads

Local MutationObserver
Only responsible for cleaning up two confirmed AdSense height pollution values

Each layer only needed to understand its own problem.

This is also why we did not revert to Plan A just because height pollution occurred.

What truly needed to be restored was not:

Plan A.

But merely:

The layout protection from Plan A that had already been proven valuable in the real production environment.

Code from the old plan should also be re-evaluated by responsibility

There was another experience from this round that I felt was worth recording.

When refactoring an old implementation, it is easy to simply categorize code as:

Plaintext
Old code
=
Should be deleted

But the reality is often not that simple.

In Plan A:

Plaintext
Global DOM observer managing SPA ads

was ultimately proven not suitable as a long-term solution.

But in the same Plan A:

Plaintext
Local protection of course height

had already solved a real AdSense production issue in advance.

So the most reasonable approach later was not:

Restoring all of A.

Nor was it:

Because we had switched to B, no code from A could be used anymore.

But rather:

Re-evaluating what responsibilities the old code actually bore, and integrating the still-valuable parts into the current architecture with new lifecycle boundaries.

This way, we neither reverted to the complex Plan A, nor lost the accumulated production experience due to the refactoring.

Finally synced to zh-CN and ja-JP

The final layout protection fix was formalized as a commit:

Plaintext
91a2583
fix: 恢复课程广告布局保护

It was then synced to production.

zh-CN finally confirmed:

  • Page layout is normal;
  • Footer no longer enters the first screen;
  • Example source code is normal;
  • SPA next page is normal;
  • Real manual ads can be displayed.

ja-JP was also synced to the current version:

  • Final page layout is normal;
  • Footer does not enter the first screen;
  • Example source code is normal;
  • Latest shared static assets have taken effect.

The specific production publish, shared-assets, Cloudflare cache, and health check processes have been documented multiple times before, so I will not expand on them again here.

What this article truly focuses on is:

Whether the page the user ultimately gets in the browser is stable.

From “finding a way to make ads appear” to “ads must not break the course”

The initial problem of this round of work was actually very simple:

Why were there no standard display ads on A Tour of Go?

Later, it step-by-step evolved into:

Plaintext
Should we abandon SPA for ads?
↓
How to add explicit ad slots to the SPA?
↓
Why was Plan A getting increasingly complex?
↓
How does Plan B consolidate the lifecycle?
↓
How to make search engines understand 103 course pages?
↓
How can Prerender coexist with Angular / CodeMirror?
↓
Why did real AdSense break page height again?
↓
How to restore only the necessary protection without reverting to Plan A?

The priorities that were ultimately established also became increasingly clear:

Plaintext
Core course functionality
        >
Page stability
        >
SEO page identity
        >
Ad display

Of course, we want ads to display normally as much as possible.

But if catering to ads leads to:

  • Anomalous example source code;
  • “Next” button failing;
  • Page height collapsing;
  • Footer moving into the first screen;

then even if the ad itself loads successfully, this implementation cannot be considered a success.

The ultimately acceptable state should be:

When Google returns filled, the page is normal; when it returns unfilled, the page is also normal; when the ad code encounters an anomaly, the course still functions normally; during consecutive SPA pagination, the ads can follow the current course without gradually intruding into the entire application lifecycle.

Reaching this point marks the true completion of this round of optimization, which began with “A Tour of Go having no standard display ads at all”.

关于作者 · 持续学习与技术实践

我是一名拥有 15 年以上开发经验的技术从业者,自 2013 年起持续运营个人技术博客,记录工作与个人项目中遇到的真实问题,以及解决问题过程中的探索、实践和思考。

除了技术写作,我也在持续开发和维护自己的独立项目,探索新技术和新工具在实际场景中的应用。我始终相信,没有不值得去解决的问题,也没有不值得去学习的技术。

如果这篇文章对你有所帮助,欢迎浏览博客中的其他文章,也欢迎交流技术经验与想法。

关于我  ·  GitHub  ·  邮件联系