Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Mar 2012
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Injecting jQuery

    I need to be able to inject the jQuery library into a page through a JavaScript file, then be able to immediately use those jQuery functions.

    My code to injecting jQuery works:
    Code:
    jq = document.createElement("script");
    jq.setAttribute("type","text/javascript");
    jq.setAttribute("src","jquery.js");
    document.getElementsByTagName('head')[0].appendChild(jq);

    After this code runs, I can do something such as "on a button click, do $(...).slideUp(...), but I cannot run $(...).slideUp(...) directly after that code.

    In my test HTML file, I have this in the head:
    Code:
    <script type="text/javascript">
    injectJQuery();
    $("#test").slideUp(1000);
    </script>

    Where injectJQuery(); is the code above that injects the jQuery. When the browser hits the "$("#test").slideUp(1000);" line, it tells me $ is undefined which means jQuery is not loaded.

    How would I go about doing this?

  • #2
    Senior Coder
    Join Date
    Dec 2010
    Posts
    2,355
    Thanks
    11
    Thanked 558 Times in 551 Posts
    Why don't you just add a <script> tag in the head? It would automatically deal with loading the script and continue only when the script has been loaded.

    Nevertheless there is a "load" event triggered when an injected script has been loaded.

    Furthermore, the element "#test" will not be available in the head section because it will only be loaded and embedded into the DOM after processing the body section. So either put the <script> to the end of the body section, or add $(document).ready() to your code.

    Try this

    Code:
    function injectJQuery(callback) {
       jq = document.createElement("script");
       jq.setAttribute("type","text/javascript");
       jq.setAttribute("src","jquery.js");
    
       jq.onload = callback;
    
       document.getElementsByTagName('head')[0].appendChild(jq);
    }
    
    injectJQuery(function() {
       $(document).ready(function() {
          $("#test").slideUp(1000);
       });
    });
    Last edited by devnull69; 03-18-2012 at 09:48 AM.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •