1

Question is: is it possible to pull in Jquery using Javascript.

Here is my code :

    <html><head></head><body>

    <div id="ttt">replace me!</div>

    <div id="apxtoo"></div>
    <script type="text/javascript">
      var sc = document.createElement('script');
      sc.src = 'http://code.jquery.com/jquery-1.5.js';
      sc.type = 'text/javascript';
      document.getElementById("apxtoo").appendChild(sc);
    </script>

    <script type="text/javascript">
    $("#ttt").text = "Cancel";
    </script>

    </body></html>

But the Jquery section does not run...any ideas how I can fix it?

David19801
  • 9,964
  • 22
  • 74
  • 121

2 Answers2

2

You need to wait for the script to load before executing any commands that are dependent on it.

http://jsfiddle.net/EZ8uL/

<div id="ttt">replace me!</div>

<div id="apxtoo"></div>
<script type="text/javascript">
  var sc = document.createElement('script');
  sc.src = 'http://code.jquery.com/jquery-1.5.js';
  sc.type = 'text/javascript';
  document.getElementById("apxtoo").appendChild(sc);

  sc.onload = function(){   // this is quick and dirty, use attachEvent or addEventListener
    $("#ttt").text("Cancel");
  }
</script>​
Shmiddty
  • 13,349
  • 1
  • 32
  • 52
0

You could as well use document.write but it is controversial, check out this tread:

Why is document.write considered a "bad practice"?

Then again, you will come across it, so it is worth knowing how it works. It is for example in the Html5 Boilerplate. https://github.com/h5bp/html5-boilerplate/blob/master/index.html

Another informative read is here: http://www.stevesouders.com/blog/2012/04/10/dont-docwrite-scripts/

I think Google Analytics had their snippet with document.write, but not anymore.

Community
  • 1
  • 1
piatek
  • 376
  • 1
  • 6