Using Polymer to include jQuery via HTML Import does not work in Safari and Firefox

I tried to include jQuery on the homepage via HTML Import, but it only worked in Chrome. Both Safari and Firefox threw a "ReferenceError: $ undefined" message on the first line of JavaScript on the main page. It turned out that the JavaScript code on the page was executed before the jQuery object was loaded in Safari or Firefox. I have used the latest 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>

      

Am I missing something obvious here? Thank!

+3


source to share


1 answer


Neither Safari nor Firefox support HTMLImports today. Instead, it platform.js

enforces this functionality using Ajax requests.

Without native browser support, there is no way to make the tag <script>

until the import has finished loading. For this reason, in order to maintain policies, you need to wait until the event happens HTMLImportsLoaded

(or put all the dependent code behind the import).

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>

      

+3


source







All Articles