使用Polymer通过HTML Imports包含jQuery不能在Safari和Firefox中使用 [英] Using Polymer to include jQuery via HTML Imports not working in Safari and Firefox

查看:71
本文介绍了使用Polymer通过HTML Imports包含jQuery不能在Safari和Firefox中使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I tried to include jQuery in the main page via HTML Imports, but it only worked in Chrome. Both Safari and Firefox threw a "ReferenceError: $ is not defined" message on the first line of the JavaScript code in the main page. It appeared that the JavaScript code on the page was executed before the jQuery object was loaded in Safari or Firefox. I was using the latest versions of Polymer(0.4) and jQuery (2.1.1). Below is a minimal example:

jquery.html

jquery.html

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

main.html

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>

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

Did I miss something obvious here? Thanks!

推荐答案

Safari和Firefox今天都不支持HTMLImports。取而代之的是 platform.js 使用Ajax请求的polyfill。

Neither Safari nor Firefox support HTMLImports today. Instead platform.js polyfills that feature using Ajax requests.

如果没有本地浏览器支持,则无法使用< script> 标记等待导入完成加载。因此,要支持polyfill,您必须等到 HTMLImportsLoaded 事件触发(或将所有相关代码置于导入后面)。

Without native browser support there is no way to make your <script> tag wait until the imports have finished loading. For this reason, to support the polyfills you have to wait until the HTMLImportsLoaded event fires (or put all your dependent code behind imports).

所以,或者:

<!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>

code.html

code.html

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

main.html

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>

这篇关于使用Polymer通过HTML Imports包含jQuery不能在Safari和Firefox中使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆