0

I created dynamically new window in JavaScript and add some HTML code in it through JavaScript, but when I insert some script link into html head, it does not load when window is open.

<script type="text/javascript">    
function newWindowMap(){

    var myWindow = window.open('','_blank');
    var head = myWindow.document.getElementsByTagName('head')[0];
    var body = myWindow.document.getElementsByTagName('body')[0];

    var jqueryScript = myWindow.document.createElement('script');
    jqueryScript.src = 'jquery.min.js';
    jqueryScript.type = "text/javascript";
    head.appendChild(jqueryScript);

    var alertScr = myWindow.document.createElement('script');
    var inlineScript = 
 document.createTextNode('$(document).ready(function(){alert("Hello World!");});');
    alertScr.appendChild(inlineScript);
    body.appendChild(alertScr);

}
 </script>

Error on console:

Uncaught ReferenceError: $ is not defined at :1:1

Dale K
  • 25,246
  • 15
  • 42
  • 71
Zeeshan
  • 1
  • 1

1 Answers1

2

$ is from JQuery, which is a popular library for JavaScript, and from the looks, you haven't imported it.

Add this into your head tag to fix the issue

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
Snel23
  • 1,381
  • 1
  • 9
  • 19
  • i already tried to do this but not solved the issue. the same problem persists.When i add jquery script in head of html, it works but when i do the same thing dynamically, it doesn't work. why is that? – Zeeshan May 22 '19 at 06:37
  • 1
    Is the jquery script inserted *before* your own JavaScript code? If it isn't, then your code will not know what `$` is – Snel23 May 22 '19 at 06:38
  • 1
    I'm looking at your code, and is it that you are trying to load the JQuery script dynamically rather than when the html document is initialized? – Snel23 May 22 '19 at 06:40
  • its inserted in the header so, obviously before to my java script – Zeeshan May 22 '19 at 06:40
  • Is [this](https://stackoverflow.com/a/10113434/9070080) what you are looking for? (Assuming you are trying to load it dynamically) – Snel23 May 22 '19 at 06:45