gpt4 book ai didi

javascript - 使用 Polymer 通过 HTML 导入包含 jQuery 在 Safari 和 Firefox 中不起作用

转载 作者:行者123 更新时间:2023-11-29 10:42:35 24 4
gpt4 key购买 nike

我尝试通过 HTML Imports 在主页中包含 jQuery,但它只在 Chrome 中有效。 Safari 和 Firefox 都在主页 JavaScript 代码的第一行抛出了“ReferenceError: $ is not defined”消息。页面上的 JavaScript 代码似乎是在 jQuery 对象加载到 Safari 或 Firefox 之前执行的。我使用的是最新版本的 Polymer(0.4) 和 jQuery (2.1.1)。下面是一个最小的例子:

jquery.html

<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>

main.html

<!DOCTYPE html>
<html>
<head>
<title>Import jQuery</title>
<script src="http://www.polymer-project.org/platform.js"></script>
<link rel="import" href="jquery.html">
</head>
<body>
<script>
$(document).ready(function() {
console.log("Hello World!");
});
</script>

</body>
</html>

我在这里错过了一些明显的东西吗?谢谢!

最佳答案

如今,Safari 和 Firefox 都不支持 HTMLImports。相反 platform.js使用 Ajax 请求的 polyfill。

没有 native 浏览器支持,就无法制作您的 <script>标记等到导入完成加载。因此,要支持 polyfill,您必须等到 HTMLImportsLoaded事件触发(或将所有依赖代码置于导入之后)。

所以,要么:

<!DOCTYPE html>
<html>
<head>
<title>Import jQuery</title>
<script src="http://www.polymer-project.org/platform.js"></script>
<link rel="import" href="jquery.html">
</head>
<body>
<script>
addEventListener('HTMLImportsLoaded', function() {
$(document).ready(function() {
console.log("Hello World!");
});
});
</script>

</body>
</html>

代码.html

<script>
$(document).ready(function() {
console.log("Hello World!");
});
</script>

main.html

<!DOCTYPE html>
<html>
<head>
<title>Import jQuery</title>
<script src="http://www.polymer-project.org/platform.js"></script>
<link rel="import" href="jquery.html">
</head>
<body>
<link rel="import" href="code.html">
</body>

关于javascript - 使用 Polymer 通过 HTML 导入包含 jQuery 在 Safari 和 Firefox 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25819898/

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