SetGlobalTag

coderljw 2024-10-13 Utils
  • Utils
  • SetGlobalTag
小于 1 分钟

# 1. SetGlobalTag

import { isUrl } from '@/utils/help'

/**
 * @name 设置标签属性
 */
export const setAttribute = (element: Element, attr: Record<string, string>) => {
  if (!element || typeof attr !== 'object' || attr === null) return
  Object.entries(attr).forEach(([qualifiedName, value]) => {
    element.setAttribute(qualifiedName, value)
  })
}

/**
 * @name 设置站点图标
 */
export const setFavicon = (href: string) => {
  if (!href) return
  const favicon = document.head.querySelector('link[rel="shortcut icon"], link[rel="icon"]')
  if (favicon) return setAttribute(favicon, { href })

  const link = document.createElement('link')
  setAttribute(link, { rel: 'icon', href })
  document.head.appendChild(link)
}

/**
 * @name 设置全局样式
 */
export const setGlobalStyle = (string: string) => {
  if (!string) return
  if (isUrl(string)) {
    const link = document.createElement('link')
    setAttribute(link, {
      ref: 'stylesheet',
      type: 'text/css',
      crossorigin: 'anonymous',
      href: string,
    })
    document.head.appendChild(link)
    return
  }

  const style = document.createElement('style')
  setAttribute(style, { type: 'text/css' })
  style.innerHTML = string
  document.head.appendChild(style)
}

/**
 * @name 设置全局脚本
 */
export const setGlobalScript = (string: string) => {
  if (!string) return
  if (isUrl(string)) {
    const script = document.createElement('script')
    setAttribute(script, {
      type: 'text/javascript',
      crossorigin: 'anonymous',
      src: string,
    })
    document.head.appendChild(script)
    return
  }

  const script = document.createElement('script')
  setAttribute(script, { type: 'text/javascript' })
  script.innerHTML = string
  document.head.appendChild(script)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
以父之名
周杰伦.mp3