简体   繁体   中英

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

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!

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM