Frage

Ich möchte Anforderungen verwenden und ich benutze JQuery. Ich möchte die kombinierte Version von RequestJS und JQuery nicht verwenden, da ich die neueste Jquery -Version nicht verwende. Was ist der beste Weg für mich, mit Anforderungen zu arbeiten?

War es hilfreich?

Lösung

Das ist auch meine genaue Frage! Ich muss auch eine ältere JQuery verwenden, aber auch "traditioneller" JavaScript -Bibliotheken. Was ist die beste Technik dafür? (Ich kann Ihre Frage bearbeiten, um sie breiter zu machen, wenn es Ihnen nichts ausmacht.) Hier ist das, was ich gelernt habe.

Der Anforderungsautor James Burke erklärte das Vorteile der kombinierten Anforderungen + JQuery -Datei. Du bekommst zwei Dinge.

  1. Ein Modul, jquery, ist verfügbar und es ist das JQuery -Objekt. Das ist sicher:

    // My module depends on jQuery but what if $ was overwritten?
    define(["jquery"], function($) {
      // $ is guaranteed to be jQuery now */
    })
    
  2. JQuery ist bereits vor einem beladen require() oder define() Sachen. Alle Module sind garantiert, dass JQuery fertig ist. Sie brauchen das nicht einmal das require/order.js Plugin Da JQuery im Grunde genommen hart codiert war, um zuerst zu laden.

Für mich ist #2 nicht sehr hilfreich. Die meisten realen Anwendungen haben viele .js Dateien das muss Laden Sie in der richtigen Reihenfolge - SAD, aber wahr. Sobald Sie Sammy oder Unscore.js benötigen, hilft die kombinierte Anforderungsdatei nicht.

Meine Lösung ist es, einfache Anforderungen zu schreiben, die meine herkömmlichen Skripte mit dem Plugin "Order" laden.

Beispiel

Angenommen, meine App hat diese Komponenten (nach Abhängigkeit).

  • Meine App, Greatapp
    • GreatApp hängt von einem Brauch ab JQuery (alte Version, die ich verwenden muss)
    • GreatApp hängt davon ab my_sammy (Sammyjs plus alle Plugins, die ich verwenden muss). Diese Muss in Ordnung sein
      1. my_sammy hängt davon ab JQuery (Sammyjs ist ein JQuery -Plugin)
      2. my_sammy hängt davon ab Sammy.js
      3. my_sammy hängt davon ab sammy.json.js
      4. my_sammy hängt davon ab sammy.storage.js
      5. my_sammy hängt davon ab sammy.mustache.js

In meinen Gedanken endet alles über das mit .js ist ein "traditionelles" Skript. Alles ohne .js ist ein RequiredJS -Plugin. Der Schlüssel ist: High-Level-Sachen (GreatApp, My_Sammy) sind Module und auf tiefere Ebenen fällt es auf traditionelle zurück .js Dateien.

Booten

Alles beginnt mit einem Booter, der sagt, dass er anfängt.

<html>
  <head>
    <script data-main="js/boot.js" src="js/require.js"></script>
  </head>
</html>

Im js/boot.js Ich platziere nur die Konfiguration und wie ich die Anwendung starten soll.

require( // The "paths" maps module names to actual places to fetch the file.
         // I made modules with simple names (jquery, sammy) that will do the hard work.
         { paths: { jquery: "require_jquery"
                  , sammy : "require_sammy"
                  }
         }

         // Next is the root module to run, which depends on everything else.
       , [ "greatapp" ]

         // Finally, start my app in whatever way it uses.
       , function(greatapp) { greatapp.start(); }
       );

Hauptanwendung

Im greatapp.js Ich habe ein normal aussehendes Modul.

define(["jquery", "sammy"], function($, Sammy) {
  // At this point, jQuery and SammyJS are loaded successfully.
  // By depending on "jquery", the "require_jquery.js" file will run; same for sammy.
  // Those require_* files also pass jQuery and Sammy to here, so no more globals!

  var start = function() {
    $(document).ready(function() {
      $("body").html("Hello world!");
    })
  }

  return {"start":start};
}

Erforderndejs Modulverpackungen in Bezug auf herkömmliche Dateien

require_jquery.js:

define(["/custom/path/to/my/jquery.js?1.4.2"], function() {
  // Raw jQuery does not return anything, so return it explicitly here.
  return jQuery;
})

require_sammy.js:

// These must be in order, so use the "order!" plugin.
define([ "order!jquery"
       , "order!/path/to/custom/sammy/sammy-0.6.2-min.js"
       , "order!/path/to/custom/sammy/plugins/sammy.json-0.6.2-min.js"
       , "order!/path/to/custom/sammy/plugins/sammy.storage-0.6.2-min.js"
       , "order!/path/to/custom/sammy/plugins/sammy.mustache-0.6.2-min.js"
       ]

       , function($) {
           // Raw sammy does not return anything, so return it explicitly here.
           return $.sammy;
         }
      );

Andere Tipps

Diese Frage ist jetzt mindestens zwei Jahre alt, aber ich habe festgestellt, dass dies ein Problem mit RequestJS 2.0 ist (Required-Jquery.js verwendet JQuery 1.8.0, aber die neueste Version ist 1.8.2).

Wenn Sie diese Frage zufällig sehen, beachten Sie das Required-Jquery.js ist jetzt nur benötigt.js und jQuery.js, zusammengedrückt. Sie können einfach Request-Jquery.js bearbeiten und die JQuery-Teile durch eine neuere Version ersetzen.

Update (30. Mai 2013): Jetzt, wo RefordeJs Wege und Shim hat empfohlen. Hier ist eine gekürzte Version der aktuellen Methode:

requirejs.config({
    "paths": {
      "jquery": "//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min"
    }
});

define(["jquery"], function($) {
    $(function() {
    });
});

Sehen http://requirejs.org/docs/jquery.html Für mehr Information.

Ich habe festgestellt, dass der beste Ansatz darin besteht, JQuery außerhalb meiner Forderung zu halten.

Fügen Sie einfach jQuery.min.js in Ihr HTML auf. Dann machen Sie eine jQuery.js -Datei mit so etwas ...

define([], function() {
    return window.$;
});

Fand Jasonsmiths Anwer enorm hilfsbereit, wahrscheinlich mehr als die Dokumentation von RequiredJS.

Es gibt jedoch Möglichkeiten, dies zu optimieren, um zu vermeiden, dass separate AJAX-Anfragen für (winzige) Define-Deklaring-Module ("Required_JQuery" "Required_Sammy") durchgeführt werden. Ich würde vermuten, dass R.Js dies in der Optimierungsphase tun würde, aber Sie können dies im Voraus tun, um nicht mit dem Basuri -System zu kämpfen.

Index.html:

<html>
  <head>
    <script data-main="js/loader.js" src="js/require.js"></script>
  </head>
</html>

lader.js:

// We are going to define( dependencies by hand, inline.
// There is one problem with that through (inferred from testing):
// Dependencies are starting to load (and execute) at the point of declaring the inline
// define, not at the point of require(
// So you may want to nest the inline-defines inside require( 
// this is, in a way, short replacement for Order plug in, but allows you to use
// hand-rolled defines, which the Order plug in, apparently does not allow.

var jQueryAndShims = ['jquery']

if(window.JSON == null){
    jQueryAndShims.push('json2')
    define(
        'json2'
        , ['js/libs/json2.min.js']
        , function() {
            return window.JSON
        }
    )
}
// will start loading the second we define it.
define(
    'jquery'
    , ['js/libs/jquery_custom.min.js']
    , function() {
        // we just pick up global jQuery here. 
        // If you want more than one version of jQuery in dom, read a more complicated solution discussed in
        // "Registering jQuery As An Async-compatible Module" chapter of
        // http://addyosmani.com/writing-modular-js/
        return window.jQuery 
    }
)

// all inline defines for resources that don't rely on other resources can go here.

// First level require(
// regardless of depends nesting in 'myapp' they will all start downloading 
// at the point of define( and exec whenever they want, 
// async in many browsers. Actually requiring it before the nested require makes
// sure jquery had *executed and added jQuery to window object* before
// all resolved depends (jquery plugins) start firing.
require(jQueryAndShims, function($) {

    // will start loading the second we define it.        
    define(
        'sammy_and_friends'
        , ['jquery','js/libs/jquery_pluginone.min.js','js/libs/jquery_plugintwo.min.js','js/libs/sammy.min.js']
        , function($) {
            // note, all plugins are unaltered, as they are shipped by developers.
            // in other words, they don't have define(.. inside.
            // since they augment global $ (window.jQuery) anyway, and 'jquery' define above picks it up
            // , we just keep on returning it.
            // Sammy is attached to $ as $.sammy, so returning just Sammy makes little sense
            return $
        }
    )

    // second level require - insures that Sammy (and other jQuery plugins) - 'sammy_and_friends' - is
    // loaded before we load Sammy plugins. I normally i would inline all sammy plugins i need 
    // (none, since i use none of them preferring jQuery's direct templating API
    // and no other Sammy plug in is really of value. )  right into sammy.js file. 
    // But if you want to keep them separate:
    require(['sammy_and_friends'], function() {

        // will start loading the second we define it.
        define(
            'sammy_extended'
            , ['sammy_and_friends','js/libs/sammy_pluginone.min.js','js/libs/sammy_plugintwo.min.js']
            , function($) {
                // as defined above, 'sammy_and_friends' actually returns (globall) jQuery obj to which
                // Sammy is attached.  So we continue to return $
                return $
            }
        )
        // will start loading the second we define it.
        define(
            'myapp'
            , ['sammy_extended', 'js/myapplication_v20111231.js'] 
            , function($, myapp_instantiator) {
                // note, myapplication may, but does not have to contain RequireJS-compatible define
                // that returns something. However, if it contains something like 
                // "$(document).ready(function() { ... " already it MAY fire before 
                // it's depends - 'sammy_extended' is fully loaded.
                // Insdead i recommend that myapplication.js returns a generator 
                // (app-object-generating function pointer)
                // that takes jQuery (with all loaded , applied plugins) 
                // The expectation is that before the below return is executed, 
                // all depends are loaded (in order of depends tree)
                // You would init your app here like so:
                return myapp_instantiator($)
                // then "Run" the instance in require( as shown below
            }
        )

        // Third level require - the one that actually starts our application and relies on
        // dependency pyramid stat starts with jQuery + Shims, followed by jQuery plugins, Sammy, 
        // followed by Sammy's plugins all coming in under 'sammy_extended'
        require(['jquery', 'myapp'], function($, myappinstance) {
            $(document).ready(function() {myappinstance.Run()})
        })
    }) // end of Second-level require
}) // end of First-level require

Schließlich myapplication.js:

// this define is a double-wrap.
// it returns application object instantiator that takes in jQuery (when it's available) and , then, that
// instance can be "ran" by pulling .Run() method on it.
define(function() {
    // this function does only two things:
    // 1. defines our application class 
    // 2. inits the class and returns it.
    return function($) {
        // 1. defining the class
        var MyAppClass = function($) {
            var me = this
            this._sammy_application = $.sammy(function() {
                this.raise_errors = true
                this.debug = true
                this.run_interval_every = 300
                this.template_engine = null
                this.element_selector = 'body'
                // ..
            })
            this._sammy_application.route(...) // define your routes ets...
            this.MyAppMethodA = function(blah){log(blah)}  // extend your app with methods if you want
            // ...
             // this one is the one we will .Run from require( in loader.js
            this.Run = function() {
                me._sammy_application.run('#/')
            }
        }
        // 2. returning class's instance
        return new MyAppClass($) // notice that this is INITED app, but not started (by .Run) 
        // .Run will be pulled by calling code when appropriate
    }
})

Diese Struktur (locker ersetzt (Duplikate?) Erfordernder Auftrags -Plugin, ermöglicht es Ihnen, die Anzahl der Dateien zu beschneiden, die Sie zum AJAX benötigen, und fügen Sie die Definition von Abhängig und Abhängigkeit von Baum zu.

Es gibt auch einen großen Bonus, um JQuery separat zu laden (was normalerweise bei 100K erhältlich ist). Schauen Sie sich hier das AMD-Cache-Projekt an https://github.com/jensarps/amd-cache Ändern Sie dann die Definition (Aussagen, um "Cache!" zu enthalten. Und es wird (für immer :)) im Browser des Benutzers stecken.

define(
    'jquery'
    , ['cache!js/libs/jquery_old.min.js']
    , function() {
        // we just pick up global jQuery here. 
        // If you want more than one version of jQuery in dom, read a more complicated solution discussed in
        // "Registering jQuery As An Async-compatible Module" chapter of
        // http://addyosmani.com/writing-modular-js/
        return window.jQuery 
    }
)

Hinweis zu jQuery 1.7.x+ Es wird sich nicht mehr an das Fensterobjekt angeschlossen, sodass die oben genannte nicht mit unmodifizierter JQuery 1.7.x+ -Datei funktioniert. Dort müssen Sie Ihre jQuery **. Js anpassen, um dies vor dem Schließen "}) (Fenster) anzupassen;":

;window.jQuery=window.$=jQuery

Wenn Sie "jQuery undefinierte" Fehler in der Konsole haben, ist es ein Zeichen.

Code -Lizenz: Public Domain.

Offenlegungen: JavaScript riecht nach "Pseudo-Code", da es sich um eine Paraphrasing (Hand-Pruning) viel detaillierterer Produktionscode handelt. Der oben dargestellte Code funktioniert nicht garantiert und wurde nicht wie vorgestellt geprüft. Prüfen, testen Sie es. Semikolons sind absichtlich weggelassen, da sie pro JS -Spezifikation nicht benötigt werden und der Code ohne sie besser aussieht.

Neben der Antwort von JHS finden Sie auch die neueren Anweisungen zur Reard-Jquery Github-Seite Aus der Datei readme.md. Es deckt sowohl den einfachsten Ansatz für die Verwendung einer kombinierten JQuery/Request.js -Datei als auch zur Verwendung eines separaten jQuery.js ab.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top