nin*_*sky 5 google-api svelte workbox sveltekit
我是 SvelteKit 的新手,正在尝试了解如何加载 Javascript 的 Google 客户端库。
谷歌告诉我这样做:
<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>
Run Code Online (Sandbox Code Playgroud)
问题是 SvelteKit 不允许一个页面上有 2 个或更多脚本标签(我不希望它成为布局页面)。
<script src="https://apis.google.com/js/api.js"></script>
<script>
import { onMount } from 'svelte';
gapi.client.init({...
</script>
Run Code Online (Sandbox Code Playgroud)
这会导致以下错误消息:
A component can only have one instance-level <script> element
Run Code Online (Sandbox Code Playgroud)
由于我的目的是使用 Workbox 创建渐进式 Web 应用程序 (PWA),因此我不想按照此处所述导入 Google 库,因为包含该库的包会变得太重。
关于如何加载 Google 客户端库有什么想法吗?也许有一个 Workbox 方法可以做到这一点?在 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>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4516 次 |
| 最近记录: |