Using Polymer to include jQuery via HTML Imports not working in Safari and Firefox

若如初见. 提交于 2019-12-10 19:17:30

问题


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

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

Did I miss something obvious here? Thanks!


回答1:


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

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).

So, either:

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

or

code.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>



来源:https://stackoverflow.com/questions/25819898/using-polymer-to-include-jquery-via-html-imports-not-working-in-safari-and-firef

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!