The mystery of '$.md5 is not a function'

2019-07-26 06:46发布

问题:

I have a js code that uses jQuery.MD5 library. It works perfectly on my server:

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://example.com/static/js/jquery.md5.js"></script>
</head>
<body>
    <script>
      // my code goes here (declaring variables and functions)
      var code = $.md5('mystring');
      // and a little more code
    </script>
</body>

But then I upload it to a web application (which I cannot control), that makes it look like this and puts it into an iframe:

<head>
  <script>
    // some extra variables are declared here
    // double-checked that nothing here can break my code
  </script>
</head>
<body>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://example.com/static/js/jquery.md5.js"></script>
    <script>
        // some code
        var code = $.md5('mystring');
        // some code
    </script>
</body>

And this code starts giving me the $.md5 is not a function error. Strange thing. Tried clearing the cache, putting jquery.md5.js code directly into mine, nothing works.

Note that all the code works on my machine, so there must be no problem with my JS.

Update: the problematic code behavior seems to be unpredictable, meaning that sometimes it works fine with no changes.

What can be wrong?

回答1:

Hm... That's a little embarrassing, but the problem was in jQuery. The one I included in my iframe conflicted with the one included in the page. Somehow this lead to "hiding" my $.md5 function after its code's end.

And yeah, I know, it was quite obvious that jQuery could cause problems.