Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 19 additions & 3 deletions docs/src/app/shared/header-tag-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,32 @@ export class HeaderTagManager {
private readonly _document = inject(DOCUMENT);

/**
* Sets the canonical link in the header.
* It supposes the header link is already present in the index.html
* Sets the canonical link in the header. If the link already exists,
* it will be updated. Otherwise, a new link will be created and inserted
* after the title tag.
*
* The function behave invariably and will always point to angular.dev,
* no matter if it's a specific version build
*/
setCanonical(absolutePath: string): void {
const pathWithoutFragment = this._normalizePath(absolutePath).split('#')[0];
const fullPath = `${MAT_ANGULAR_DEV}/${pathWithoutFragment}`;
this._document.querySelector('link[rel=canonical]')?.setAttribute('href', fullPath);
let canonicalLink = this._document.querySelector<HTMLLinkElement>('link[rel=canonical]');

if (canonicalLink) {
canonicalLink.setAttribute('href', fullPath);
} else {
canonicalLink = this._document.createElement('link');
canonicalLink.setAttribute('rel', 'canonical');
canonicalLink.setAttribute('href', fullPath);

const title = this._document.head.querySelector('title');
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seems a bit convoluted. We can just do document.head.appendChild(canonicalLink).

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I had that first but then thought that the search engine might not process the canonical (with the same priority) if it's at the very end of the long even below the long <script> tag. But given that this would be only for a search engine that runs JS - this is probably silly.

if (title) {
title.insertAdjacentElement('afterend', canonicalLink);
} else {
this._document.head.appendChild(canonicalLink);
}
}
}

private _normalizePath(path: string): string {
Expand Down
1 change: 0 additions & 1 deletion docs/src/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
<head>
<meta charset="utf-8">
<title>Angular Material UI Component Library</title>
<link rel="canonical" href="https://material.angular.dev">
<base href="/">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
Expand Down
Loading