Search code examples
javascriptjqueryhtmlinternet-explorer-9

use document.write() to write html in to iframe, but jquery not working in IE9


I have stored a html page in local system, and i try to get the contents then write to an iframe.

<html>
<head>
    <title></title>
    <script src="js/jquery.min.js" type="text/javascript"></script>
    <link href="styles/myStlye.css" rel="stylesheet" type="text/css" />
</head>
<body><button id="buttonClick">Click Me</button></body>
<script>
    $(document).ready(function(){
        $("#buttonClick").click(function(){
            alert("Button clicked.");
        });
    });
</script>
</html>

i use document.write() to write the html code to the iframe, but error SCRIPT5009: '$' is undefined occur when page load in IE9, but work fine in google chrome & firefox.


Solution

  • The issue might be that IE is executing the JS code before loading in jquery, try loading it in dynamically and listening for onload:

    <html>
    
    <head>
      <title></title>
      <link href="styles/myStlye.css" rel="stylesheet" type="text/css" />
    </head>
    
    <body>
      <button id="buttonClick">Click Me</button>
      <script>
        var script = document.createElement("script");
    
        script.src = "js/jquery.min.js";
    
        script.onreadystatechange = function () {
          if (this.readyState == 'complete' || this.readyState == 'loaded') {
            $("#buttonClick").click(function () {
              alert("Button clicked.");
            });
          }
        };
        script.onload = function () {
          $("#buttonClick").click(function () {
            alert("Button clicked.");
          });
        };
        document.querySelector('body').appendChild(script);
      </script>
    </body>
    
    </html>