不同环境同一函数的加载优化 bd5c715fbec446368fcc0b8477e46f66

不同环境同一函数的加载优化

以前写了一个 h5 App ,要和原生 App 进行交互。 代码是这样的:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import type { IAppVersion, ICompany } from '@/models/My';import iosBridge from '../helpers/IosWebview.js';export function isIos() {
const ua = navigator.userAgent; const isIOS = !!ua.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); return isIOS;}
/** * 返回状态栏高度 */export function getStatusHeight() {
return new Promise((resolve) => {
if (isIos()) {
try {
iosBridge((bridge: any) => {
bridge.callHandler('getStatusHeight', null, function (data: number) {
resolve(data); }); }); } catch (e) {
showToast('获取手机状态栏高度失败'); }
} else {
try {
const data = LogisticsBaseJS.getStatusHeight(); resolve(data); } catch (e) {
showToast('获取手机状态栏高度失败'); }
}
});}

是在函数里面进行的平台判断。 可这样每调用一次函数, 就得判断一次。
今天突然记起来这段代码。 于是修改了一下

1
2
3
4
5
6
import * as iosFuncs from './jsBridge/ios';import * as androidFunc from './jsBridge/android';export function isIos() {
const ua = navigator.userAgent; const isIOS = !!ua.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); return isIOS;}
const isIosPlatform = isIos();type IFunc = typeof iosFuncs
function getPlatformFunc<T extends keyof IFunc>(funcName: T): IFunc[T] {
return isIosPlatform ? iosFuncs[funcName] : androidFunc[funcName];}
export const getStatusHeight = getPlatformFunc('a');

将同一个函数分平台写在不同的文件里面。
这样初次加载的时候就会将对应平台的函数 export 出来。
节省了函数的行数,又少了一次判断。

拓展链接 7.64 dNw:/ 如何使用IIFE提升性能? # JavaScript#
前端开发工程师# 编程# 程序员# web前端# 前端
https://v.douyin.com/Btjj7YE/
复制此链接,打开Dou音搜索,直接观看视频!