gpt4 book ai didi

google-api - 如何使用 SvelteKit 加载 Google API 客户端库

转载 作者:行者123 更新时间:2023-12-02 01:48:52 25 4
gpt4 key购买 nike

我是 SvelteKit 的新手,正在尝试了解如何为 Javascript 加载 Google 客户端库。

谷歌 tells me这样做:

<head>
<script src="https://apis.google.com/js/api.js"></script>
<script>
function start() {
// Initializes the client with the API key and the Translate API.
gapi.client.init({
'apiKey': 'YOUR_API_KEY',
'discoveryDocs': ['https://www.googleapis.com/discovery/v1/apis/translate/v2/rest'],
}).then(function() {
// Executes an API request, and returns a Promise.
// The method name `language.translations.list` comes from the API discovery.
return gapi.client.language.translations.list({
q: 'hello world',
source: 'en',
target: 'de',
});
}).then(function(response) {
console.log(response.result.data.translations[0].translatedText);
}, function(reason) {
console.log('Error: ' + reason.result.error.message);
});
};

// Loads the JavaScript client library and invokes `start` afterwards.
gapi.load('client', start);
</script>
</head>

问题是 SvelteKit 不允许页面上有 2 个或更多脚本标签(我不希望它是布局页面)。

<script src="https://apis.google.com/js/api.js"></script>
<script>
import { onMount } from 'svelte';

gapi.client.init({...
</script>

这会导致以下错误消息:

A component can only have one instance-level <script> element

因为我的目的是使用 Workbox 创建一个渐进式网络应用程序 (PWA),所以我不想按照描述导入 Google 库 here因为包含这个库的包会变得太重。

关于如何加载 Google 客户端库的任何想法?也许有一种工作箱的方法可以做到这一点?在 Google 或 YouTube 上找不到 SvelteKit 示例。

提前致谢

最佳答案

svelte:head 标签允许您在加载组件时向文档头部添加资源。这个例子应该有效:

<script>
const start = async () => {
// Initializes the client with the API key and the Translate API.
// @ts-ignore
gapi.client.init({
'apiKey': 'YOUR_API_KEY',
'discoveryDocs': ['https://www.googleapis.com/discovery/v1/apis/translate/v2/rest'],
}).then(function() {
// Executes an API request, and returns a Promise.
// The method name `language.translations.list` comes from the API discovery.
return gapi.client.language.translations.list({
q: 'hello world',
source: 'en',
target: 'de',
});
}).then(function(response) {
console.log(response.result.data.translations[0].translatedText);
}, function(reason) {
console.log('Error: ' + reason.result.error.message);
});
};

const initializeGapi = async () => {
gapi.load('client', start);
}
</script>

<svelte:head>
<script src="https://apis.google.com/js/api.js" on:load={initializeGapi}></script>
</svelte:head>

关于google-api - 如何使用 SvelteKit 加载 Google API 客户端库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70570231/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com