programing

요구사항을 사용하는 방법JS와 jQuery가 같이?

mailnote 2023. 9. 18. 22:37
반응형

요구사항을 사용하는 방법JS와 jQuery가 같이?

require를 사용하고 싶습니다.JS와 저는 jQuery를 사용하고 있습니다.요구사항의 결합 버전을 사용하고 싶지 않습니다.저는 최신 jQuery 버전을 사용하지 않기 때문에 JS와 jQuery.requireJS를 사용하는 가장 좋은 방법은 무엇입니까?

그것도 나의 정확한 질문입니다!나는 또한 더 오래된 jQuery 뿐만 아니라 더 많은 "전통적인" 자바스크립트 라이브러리를 사용해야 합니다.어떻게 하는 것이 가장 좋을까요? (괜찮으시다면 질문 내용을 좀 더 폭넓게 수정해 드리겠습니다.)여기 제가 배운 것이 있습니다.

Require JS의 저자인 James Burke는 결합된 Require의 장점에 대해 설명했습니다.JS + jQuery 파일.두 가지가 있습니다.

  1. ,jquery를 사용할 수 입니다. , jQuery 입니다.안전합니다.

    // My module depends on jQuery but what if $ was overwritten?
    define(["jquery"], function($) {
      // $ is guaranteed to be jQuery now */
    })
    
  2. 가 jQuery 되었습니다 되어 있습니다.require()아니면define()모든 모듈은 jQuery가 준비된 것으로 보장됩니다.당신은 필요하지도 않아요.require/order.jsplugin은 jQuery가 기본적으로 하드코딩되어 있어서 먼저 로드합니다.

저에게 2번은 큰 도움이 되지 않습니다.대부분의 실제 애플리케이션은 많은 수의 .js파일을 올바른 순서로 로드해야 합니다. 슬프지만 참입니다.Sammy 또는 Underscore.js가 필요한 순간, 결합된 Require.JS+jQuery 파일은 도움이 되지 않습니다.

나의 해결책은 간단한 Require를 쓰는 것입니다."order" 플러그인을 사용하여 내 전통적인 스크립트를 로드하는 JS 래퍼.

내 앱에 이러한 구성 요소가 있다고 가정합니다(의존도 기준).

  • 나의 앱, 멋진
    • great app은 사용자 지정 jquery에 따라 다릅니다(구 버전을 사용해야 함).
    • great app은 my_sammy에 달려있습니다 (SammyJS와 내가 사용해야 하는 모든 플러그인).이것들은 순서대로 있어야 합니다.
      1. my_sammy는 jquery에 달려있습니다 (sammy)JS는 jQuery 플러그인)
      2. my_jamy는 sammy.js에 달려있습니다.
      3. my_jsimmy는 sammy.json.js에 달려있습니다.
      4. my_storage는 sammy.storage.js에 따라 달라집니다.
      5. my_graphics는 sammy.js에 달려있습니다.

내 마음속에, 그 위에 있는 모든 것들은 끝이 납니다..js"전통적인" 스크립트입니다.이 없는 것.js required is 필수 입니다.JS 플러그인.의 콘텐츠app, 이며, 더다로 높은 수준의 콘텐츠(great app, my_sammy)는 모듈이며, 더 깊은 수준에서는 기존 수준으로 돌아갑니다..js파일

부팅

이 모든 것은 부트가 Require라고 말하는 것에서 시작됩니다.JS 시작하는 법.

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

js/boot.js저는 애플리케이션을 시작하는 방법과 구성만 넣었습니다.

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(); }
       );

주 응용 프로그램

greatapp.js저는 평범해 보이는 모듈을 가지고 있습니다.

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};
}

기존 파일 주변에 JS 모듈 래퍼 필요

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;
         }
      );

이 질문은 적어도 2년이 지났지만 RequireJS 2.0에서 여전히 문제가 되고 있음을 알게 되었습니다(require-jquery.js는 jQuery 1.8.0을 사용하지만 최신 버전은 1.8.2입니다).

이 질문이 나타나면 require-jquery.js는 이제 함께 으깬 require.js와 jquery.js입니다.require-jquery.js를 편집하고 jQuery parts를 최신 버전으로 교체하면 됩니다.

업데이트(2013년 5월 30일):이제 그 요구사항JS에는 path와 shim이 있고 jQuery와 jQuery 플러그인을 가져올 수 있는 새로운 방법이 있으며 이전 방법은 더 이상 필요하지도 않고 권장되지도 않습니다.현재 방법의 요약 버전은 다음과 같습니다.

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

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

자세한 정보는 http://requirejs.org/docs/jquery.html 을 참조하십시오.

jQuery를 내 요구 사항에서 제외하는 것이 최선의 방법임을 알게 되었습니다.JS 빌드.

HTML에 jquery.min.js를 포함시키세요. 그러면, jquery.js 파일을 이런 것으로 만드세요.

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

Jason Smith의 답변이 매우 도움이 된다는 것을 알게 되었습니다. 아마 Require보다 더 도움이 될 것입니다.JS의 문서.

그러나 정의 선언 모듈("require_jquery" "require_sammy")에 대한 별도의 AJAX 요청이 발생하지 않도록 최적화하는 방법이 있습니다.최적화 단계에서 r.js가 할 것이라고 생각하지만 Path, BaseURI 시스템과 싸우지 않기 위해서는 미리 할 수 있습니다.

index.debook:

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

loader.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

드디어 나의 지원서.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
    }
})

이 구조(복사?)를 느슨하게 대체합니다.요구하다JS의 Order 플러그인(그러나)을 사용하면 AJAX에 필요한 파일 수를 제거할 수 있으므로 종속 및 종속 트리의 정의에 더 많은 제어 기능을 추가할 수 있습니다.

또한 jQuery를 별도로 로드할 때(일반적으로 100k로 제공됨), 서버에서 캐싱을 제어하거나 브라우저의 로컬 스토리지에 jQuery를 캐싱할 수 있습니다.여기 https://github.com/jensarps/AMD-cache 에서 AMD-Cache 프로젝트를 살펴본 다음 정의(문을 "crystal!"을 포함하도록 변경하면 사용자의 브라우저에 (crystal :) 고정됩니다.

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 
    }
)

jQuery 1.7.x+ 윈도우 오브젝트에 더 이상 첨부되지 않으므로 수정되지 않은 jQuery 1.7.x+ 파일에서는 위 내용이 작동하지 않습니다.여기서 jquery**.js를 "}"()(창)을 닫기 전에 이를 포함하도록 사용자 지정해야 합니다.

;window.jQuery=window.$=jQuery

콘솔에 "jQuery undefined" 오류가 있는 경우 사용 중인 jQuery 버전이 창에 자체가 연결되지 않는 기호입니다.

코드 라이선스: 퍼블릭 도메인입니다.

개시내용: 상기 자바스크립트는 훨씬 더 상세한 생산코드의 패러프레이징(손-가지치기)이기 때문에 "사이비 코드" 냄새가 납니다.위에 제시된 코드는 작동이 보장되지 않으며, 제시된 대로 작동하도록 테스트되지 않았습니다.감사합니다, 시험해 보세요.세미콜론은 JS 사양에 따라 필요하지 않고 코드가 없는 것이 더 보기 좋으므로 일부러 생략합니다.

jhs의 답변 외에도 README.md 파일에서 require-jquery github 페이지의 최신 지침을 참조하십시오.여기에는 결합된 jquery/require.js 파일을 사용하는 가장 간단한 방법과 별도의 jquery.js를 사용하는 방법이 모두 포함됩니다.

언급URL : https://stackoverflow.com/questions/4535926/how-do-i-use-requirejs-and-jquery-together

반응형