How to include jquery.js in another js file?

后端 未结 4 746
时光说笑
时光说笑 2020-12-03 14:48

I want to include jquery.js in myjs.js file. I wrote the code below for this.

  var theNewScript=document.createElement(\"script\");
  theNewScript.type=\"te         


        
相关标签:
4条回答
  • 2020-12-03 15:26

    The problem is that the script doesn't load instantly, it takes some time for the script file to download into your page and execute (in case of jQuery to define $).

    I would recommend you to use HeadJS. then you can do:

    head.js("/path/to/jQuery.js", function() {
       $.get('myfile.php');
    });
    
    0 讨论(0)
  • 2020-12-03 15:26

    Simple answer, Dont. The jQuery file is very touchy to intruders so dont try. Joining other files into jQuery file will often cause errors in the JS console, PLUS jQuery isn't initialized until the file is loaded into main document.

    Sorry, scratch that. Didnt quite know what you were doing.

    Try this:

    var s = document.createElement('script');
    s.type = 'text/javascript';
    s.async = true;
    s.src = 'http://domain.com/jquery.js';
    (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(s);
    
    0 讨论(0)
  • 2020-12-03 15:33

    I used this code before, and it worked:

    var t=document;
    var o=t.createElement('script');
    o=t.standardCreateElement('script');
    o.setAttribute('type','text/javascript');
    o.setAttribute('src','http://www.example.com/js/jquery-1.3.2.js');
    t.lastChild.firstChild.appendChild(o);
    
    0 讨论(0)
  • 2020-12-03 15:38

    Appending a script tag inside the document head programmatically does not necessarily mean that the script will be available immediately. You should wait for the browser to download that file, parse and execute it. Some browsers fire an onload event for scripts in which you can hookup your logic. But this is not a cross-browser solution. I would rather "poll" for a specific symbol to become available, like this:

    var theNewScript = document.createElement("script");
    theNewScript.type = "text/javascript";
    theNewScript.src = "http://example.com/jquery.js";
    document.getElementsByTagName("head")[0].appendChild(theNewScript);
    // jQuery MAY OR MAY NOT be loaded at this stage
    var waitForLoad = function () {
        if (typeof jQuery != "undefined") {
            $.get("myfile.php");
        } else {
            window.setTimeout(waitForLoad, 1000);
        }
    };
    window.setTimeout(waitForLoad, 1000);
    
    0 讨论(0)
提交回复
热议问题