How to add jQuery in JS file

后端 未结 19 643
星月不相逢
星月不相逢 2020-12-04 05:47

I have some code specific to sorting tables. Since the code is common in most pages I want to make a JS file which will have the code and all the pages using it can referen

相关标签:
19条回答
  • 2020-12-04 06:12

    Here is the solution, that I adopted as a combination of some proposed solutions in some other forums.

    This way you can reference both css files and other js files in one js file, thus making change next time only in a single place. Please let me know if you have any concerns on it.

    I have done following:

    1. I have created a js with name jQueryIncluder.js
    2. declared and executed following code in this file

      function getVirtualDirectory() {
        var vDir = document.location.pathname.split('/');
        return '/' + vDir[1] + '/';
      }
      
      function include_jQueryFilesToPage() {
        var siteAddress = location.protocol + '//' + document.location.hostname + getVirtualDirectory(); 
        var jqCSSFilePath =  siteAddress + 'includes/jQueryCSS/ehrgreen-theme/jquery-ui-1.8.2.custom.css';
        var jqCoreFilePath = siteAddress + 'includes/jquery-1.4.1.min.js';
        var jqUIFilePath =   siteAddress + 'includes/jquery-ui-1.8.2.custom.min.js';
        var head  = document.getElementsByTagName('head')[0]; 
      
        // jQuery CSS jnclude
        var jqCSS = 'cssIDJQ';  // you could encode the css path itself to generate id.
        if (!document.getElementById(jqCSS)) { 
          var link  = document.createElement('link'); 
          link.id  = jqCSS; 
          link.rel  = 'stylesheet'; 
          link.type = 'text/css'; 
          link.href = jqCSSFilePath; 
          link.media = 'all'; 
          head.appendChild(link); 
        } 
      
        // Core jQuery include
        var jqc = "coreFileRefIDJQ";  
        if (!document.getElementById(jqc)) 
          document.write('<scr' + 'ipt type="text/javascript" id="' + jqc + '" src="' + jqCoreFilePath + '"></scr' + 'ipt>');
      
        // jQueryUI include
        var jqUI = "uiFileRefIDJQ";  
        if (!document.getElementById(jqUI)) 
          document.write('<scr' + 'ipt type="text/javascript" id="' + jqUI + '" src="' + jqUIFilePath + '"></scr' + 'ipt>');
      }
      
      include_jQueryFilesToPage();
      
    3. I referenced the above jQueryIncluder.js file in another js or xsl file of my .Net project as following:

      <script type="text/javascript" src="~/includes/jQueryIncluder.js"></script>
      

    I hope my effort is appreciated.

    Thanks

    0 讨论(0)
  • 2020-12-04 06:13

    In if you want to add reference to any js file, say, from your project, you may also add it directly using reference tag, in Visual Studio IDE this is handled automatically by dragging and dropping the external file from solution explorer to current file (This works for mark up files, .js & .css files too)

    /// <reference path="jquery-2.0.3.js" />
    
    0 讨论(0)
  • 2020-12-04 06:16

    You can use the below code to achieve loading jQuery in your JS file. I have also added a jQuery JSFiddle that is working and it's using a self-invoking function.

    // Anonymous "self-invoking" function
    (function() {
        var startingTime = new Date().getTime();
        // Load the script
        var script = document.createElement("SCRIPT");
        script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js';
        script.type = 'text/javascript';
        document.getElementsByTagName("head")[0].appendChild(script);
    
        // Poll for jQuery to come into existance
        var checkReady = function(callback) {
            if (window.jQuery) {
                callback(jQuery);
            }
            else {
                window.setTimeout(function() { checkReady(callback); }, 20);
            }
        };
    
        // Start polling...
        checkReady(function($) {
            $(function() {
                var endingTime = new Date().getTime();
                var tookTime = endingTime - startingTime;
                window.alert("jQuery is loaded, after " + tookTime + " milliseconds!");
            });
        });
    })();

    Other Option : - You can also try Require.JS which is a JS module loader.

    0 讨论(0)
  • just copy the code from the two files into your file at the top.

    or use something like this http://code.google.com/p/minify/ to combine your files dynamically.

    Josh

    0 讨论(0)
  • 2020-12-04 06:21
    /* Adding the script tag to the head as suggested before */
    
        var head = document.getElementsByTagName('head')[0];
        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = "http://code.jquery.com/jquery-2.2.1.min.js";
    
        // Then bind the event to the callback function.
        // There are several events for cross browser compatibility.
        script.onreadystatechange = handler;
        script.onload = handler;
    
        // Fire the loading
        head.appendChild(script);
    
        function handler(){
           console.log('jquery added :)');
        }
    
    0 讨论(0)
  • 2020-12-04 06:22

    I believe what you want to do is still to incude this js file in you html dom, if so then this apporach will work.

    1. Write your jquery code in your javascript file as you would in your html dom
    2. Include jquery framework before closing body tag
    3. Include javascript file after including jqyery file

    Example: //js file

         $(document).ready(function(){
         alert("jquery in js file");
         });
    

    //html dom

        <body>
       <!--some divs content--->
    
       <script src=/path/to/jquery.js ></script>
       <script src=/path/to/js.js ></script>
       </body>
    
    0 讨论(0)
提交回复
热议问题