Quelle est la méthode préférée pour ajouter des fichiers javascript personnalisés au site?
-
-
Jetez un œil à [ma question d'il y a quelquesjours] (http://wordpress.stackexchange.com/questions/441/how-to-link-external-jquery-javascript-files-with-wordpress),la réponse àunepartie de votre questionest là: - [** Comment lier desfichiersjQuery/Javascriptexternes avec WordPress **] (http://wordpress.stackexchange.com/questions/441/how-to-link-external-jquery-javascript-fichiers-avec-wordpress)Take a look at [my question from a few days ago](http://wordpress.stackexchange.com/questions/441/how-to-link-external-jquery-javascript-files-with-wordpress), the answer to part of your question is there: - [**How to Link External jQuery/Javascript files with WordPress**](http://wordpress.stackexchange.com/questions/441/how-to-link-external-jquery-javascript-files-with-wordpress)
- 0
- 2010-08-19
- Ben Everard
-
Excellente question!C'est une questiontrès courante que lesgens demandentet quenous devons absolument avoirbien documentéeici.Great question! It's a very common one people ask and something that we definitely need to have well documented here.
- 4
- 2010-08-19
- MikeSchinkel
-
THX.Je l'ai déjà vu,mais celane couvraitpasentièrementma question.Thx. I saw that already, but it didn't cover my question fully.
- 0
- 2010-08-19
- naugtur
-
C'estbon,je savais que celane répondraitpas àtoutes vos questions,maispour lespersonnes qui surferont à l'avenir,il y a une référence à l'autre article :-)That's ok, I knew it wouldn't answer all of your question but for people surfing in in the future there's a reference to the other post :-)
- 0
- 2010-08-19
- Ben Everard
-
Voir également http://wordpress.stackexchange.com/questions/575/why-isnt-is-home-working-correctlyAlso see http://wordpress.stackexchange.com/questions/575/why-isnt-is-home-working-correctly
- 0
- 2010-08-23
- naugtur
-
3 réponses
- votes
-
- 2010-11-13
Pour compléter lamerveilleuseillustration de Mikes de l'utilisation desfiles d'attente,je souhaitejuste souligner que les scriptsinclus comme dépendancesn'ontpasbesoin d'êtremisen file d'attente ...
Je vais utiliser l'exemple sous letitre Scripts dans unplugin dans la réponse de Mike.
define('MY_PLUGIN_VERSION','2.0.1'); add_action( 'wp_enqueue_scripts', 'my_plugin_enqueue_scripts' ); function my_plugin_enqueue_scripts() { wp_enqueue_script('jquery'); wp_enqueue_script('jquery-ui-sortable'); wp_enqueue_script('my-script',plugins_url('/js/my-script.js',__FILE__),array('jquery','jquery-ui-sortable'),MY_PLUGIN_VERSION); }
Cecipeut être réduitpour être lu.
define('MY_PLUGIN_VERSION','2.0.1'); add_action( 'wp_enqueue_scripts', 'my_plugin_enqueue_scripts' ); function my_plugin_enqueue_scripts() { wp_enqueue_script('my-script', plugins_url( '/js/my-script.js', __FILE__ ), array('jquery','jquery-ui-sortable'), MY_PLUGIN_VERSION); }
Lorsque vous définissez des dépendances,WordPress lestrouveet lesmet enfile d'attentepour votre script,vousn'avez doncpasbesoin defaire d'appelsindépendantspour ces scripts.
Deplus,certains d'entre vous se demandentpeut-être si la définition deplusieurs dépendancespourraitentraîner la sortie des scripts dans lemauvais ordre,laissez-moi vous donner unexempleici
wp_enqueue_script( 'first-script', 'example/path/example_script_1.js', array('second-script','third-script') );
Si le script deux dépendait du scripttrois (c'est-à-dire que le scripttrois devrait se chargeren premier),celan'auraitpas d'importance,WordPress déterminera lespriorités demiseen file d'attentepour ces scriptset les affichera dans lebon ordre,bref,tout obtient élaboré automatiquementpour vouspar WordPress.
To compliment Mikes wonderful illustration of using enqueues i just wish to point out that scripts included as dependancies do not need to be enqueued...
I'll use the example under the Scripts in a Plugin heading in Mike's answer.
define('MY_PLUGIN_VERSION','2.0.1'); add_action( 'wp_enqueue_scripts', 'my_plugin_enqueue_scripts' ); function my_plugin_enqueue_scripts() { wp_enqueue_script('jquery'); wp_enqueue_script('jquery-ui-sortable'); wp_enqueue_script('my-script',plugins_url('/js/my-script.js',__FILE__),array('jquery','jquery-ui-sortable'),MY_PLUGIN_VERSION); }
This can be trimmed down to read..
define('MY_PLUGIN_VERSION','2.0.1'); add_action( 'wp_enqueue_scripts', 'my_plugin_enqueue_scripts' ); function my_plugin_enqueue_scripts() { wp_enqueue_script('my-script', plugins_url( '/js/my-script.js', __FILE__ ), array('jquery','jquery-ui-sortable'), MY_PLUGIN_VERSION); }
When you set dependancies, WordPress will find and enqueue them ready for your script, so you don't need to make any independent calls for these scripts.
Additionally, some of you may be wondering if setting a multiple dependancies might cause scripts to output in the wrong order, here let me give an example
wp_enqueue_script( 'first-script', 'example/path/example_script_1.js', array('second-script','third-script') );
If script two were dependant on script three(ie. script three should load first), this wouldn't matter, WordPress will determine the enqueue priorities for those scripts and output them in the correct order, in short, it all gets worked out automagically for you by WordPress.
-
Jepense que «init»n'estpas lebonendroitpourenvoyer lafile d'attente.I think `init` is not the proper place to dispatch the enqueue.
- 0
- 2013-09-21
- brasofilo
-
Le code a étéinitialement copié àpartir de la réponse de Mike,puis ajustépourillustrer unpoint.Vous avez cependant raison,j'ai doncmis àjour la réponsepour utiliser un crochetmeilleuret plus correct.Code was originally copied from Mike's answer, then adjusted to illustrate a point. You are correct however, so i've updated the answer to use a better and more correct hook.
- 0
- 2014-01-28
- t31os
-
- 2016-10-31
Pour lespetitsmorceaux de scripts,que vousne voudrezpeut-êtrepasinclure dans unfichier séparé,parexempleparce qu'ils sontgénérés dynamiquement,WordPress 4.5et proposeen outre
wp_add_inline_script
.Cettefonction verrouille le script sur un autre script.Supposons,parexemple,que vous développez unthèmeet que vous souhaitez que votre clientpuisseinsérer sespropres scripts (comme Google Analytics ou AddThis) via lapage d'options.Vouspouvezensuite utiliser
wp_add_inline_script
pour verrouiller ce script dans votrefichierjsprincipal (disonsmainjs
) comme ceci:$custom_script = get_option('my-script') if (!empty($custom_script)) wp_add_inline_script ('mainjs', $custom_script);
For small pieces of scripts, which you may not want to include in a separate file, for instance because they are generated dynamically, WordPress 4.5 and further offers
wp_add_inline_script
. This function basically latches the script to another script.Let's say, for instance, that you are developing a theme and want your customer to be able to insert his own scripts (like Google Analytics or AddThis) through the options page. You could then use
wp_add_inline_script
to latch that script to your main js-file (let's saymainjs
) like this:$custom_script = get_option('my-script') if (!empty($custom_script)) wp_add_inline_script ('mainjs', $custom_script);
-
- 2017-04-17
$jquery_script_path='/wp-includes/js/jquery/jquery.js?ver=1.12.4'; $jquery_dependent_script_paths=[ get_theme_file_uri ('/assets/js/global.js'), get_theme_file_uri ('/assets/js/jquery.scrollTo.js'), get_theme_file_uri ('/assets/js/skip-link-focus-fix.js'), get_theme_file_uri ('/assets/js/navigation.js') ]; $jquery_dependent_script_paths_json=json_encode ($jquery_dependent_script_paths); $inline_scripts=& lt; & lt; & lt; EOD & lt; script > (fonction () { 'use strict'; if (! window.fetch) return; /** * Récupérer Inject v1.6.8 * Droits d'auteur (c) 2017 Josh Habdas * @licence ISC */ varfetchInject=function () {"use strict"; conste=function (e,t,n,r,o,i,c) {i=t.createElement (n),c=t.getElementsByTagName (n) [ 0],i.type=r.blob.type,i.appendChild (t.createTextNode (r.text)),i.onload=o (r),c? C.parentNode.insertBefore (i,c):t .head.appendChild (i)},t=function (t,n) {if (!t ||! Array.isArray (t)) return Promise.reject (new Error ("`inputs`mustbe an array ") );if (n & amp; & amp;! (ninstance de Promise)) return Promise.reject (new Error ("`promise`mustbe apromise ")); const r=[],o=n? []. concat (n): [],i=[]; returnt.forEach (e=> o.push (window.fetch (e) .then (e=> {return [e.clone ().text (),e.blob ()]}).then (e=> {retourne Promise.all (e) .then (e=> {r.push ({text:e [0],blob:e [1]} )})}))),Promise.all (o) .then (()=> {return r.forEach (t=> {i.push ({then:n=> {"texte/css")===t.blob.type?e (fenêtre,document,"style",t,n):e (fenêtre,document,"script",t,n)}})}),Promise.all (i) })}; retournet} (); fetchInject ( $jquery_dependent_script_paths_json ,fetchInject ([ "{$jquery_script_path}" ])); }) (); & lt;/script > EOD;
Etpuisinsérez-les dans latête,parfois avec des styles comme celui-ci:
fonction wc_inline_head () { global $inline_scripts; echo "{$inline_scripts}"; global $inline_styles; echo "{$inline_styles}"; }
Ilen résulte une cascade qui ressemble à ceci,chargeanttouten mêmetempsmais contrôlant l'ordre d'exécution:
Remarque: Celanécessite l'utilisation de l'API Fetch,quin'estpas disponible danstous lesnavigateurs.
My preferred way is to achieve good performance, so rather than using
wp_enqueue_script
I use HEREDOC with the Fetch API to load everything asynchronously in parallel:$jquery_script_path = '/wp-includes/js/jquery/jquery.js?ver=1.12.4'; $jquery_dependent_script_paths = [ get_theme_file_uri( '/assets/js/global.js' ), get_theme_file_uri( '/assets/js/jquery.scrollTo.js' ), get_theme_file_uri( '/assets/js/skip-link-focus-fix.js' ), get_theme_file_uri( '/assets/js/navigation.js' ) ]; $jquery_dependent_script_paths_json = json_encode($jquery_dependent_script_paths); $inline_scripts = <<<EOD <script> (function () { 'use strict'; if (!window.fetch) return; /** * Fetch Inject v1.6.8 * Copyright (c) 2017 Josh Habdas * @licence ISC */ var fetchInject=function(){"use strict";const e=function(e,t,n,r,o,i,c){i=t.createElement(n),c=t.getElementsByTagName(n)[0],i.type=r.blob.type,i.appendChild(t.createTextNode(r.text)),i.onload=o(r),c?c.parentNode.insertBefore(i,c):t.head.appendChild(i)},t=function(t,n){if(!t||!Array.isArray(t))return Promise.reject(new Error("`inputs` must be an array"));if(n&&!(n instanceof Promise))return Promise.reject(new Error("`promise` must be a promise"));const r=[],o=n?[].concat(n):[],i=[];return t.forEach(e=>o.push(window.fetch(e).then(e=>{return[e.clone().text(),e.blob()]}).then(e=>{return Promise.all(e).then(e=>{r.push({text:e[0],blob:e[1]})})}))),Promise.all(o).then(()=>{return r.forEach(t=>{i.push({then:n=>{"text/css"===t.blob.type?e(window,document,"style",t,n):e(window,document,"script",t,n)}})}),Promise.all(i)})};return t}(); fetchInject( $jquery_dependent_script_paths_json , fetchInject([ "{$jquery_script_path}" ])); })(); </script> EOD;
And then insert them into the head, sometimes along with styles like this:
function wc_inline_head() { global $inline_scripts; echo "{$inline_scripts}"; global $inline_styles; echo "{$inline_styles}"; }
Resulting in waterfall that looks like this, loading everything at once but controlling the execution order:
Note: This requires use of the Fetch API, which is not available in all browsers.
J'ai déjà ajoutémes scripts,maisje voulais connaître laméthodepréférée.
Je viens demettre unebalise
<script>
directement dans leheader.php
demonmodèle.Existe-t-il uneméthodepréféréepourinsérer desfichiersjsexternes oupersonnalisés?
Comment lier unfichierjs à une seulepage?(J'ai lapage d'accueilen tête)