Ori.livneh has uploaded a new change for review.

  https://gerrit.wikimedia.org/r/196989

Change subject: Optimize order of styles and scripts
......................................................................

Optimize order of styles and scripts

The current ordering of scripts and stylesheets in <head> causes all major
browsers to serialize and defer requests that could be performed in parallel.

The problem is that external stylesheets are loaded before inline scripts. As
Steven Souders explains, "all major browsers preserve the order of CSS and
JavaScript. The stylesheet has to be fully downloaded, parsed, and applied
before the inline script is executed. And the inline script must be executed
before the remaining resources can be downloaded. Therefore, resources that
follow a stylesheet and inline script are blocked from downloading."[1]

In other words: the browser could start loading body images, but it refuses to
do that until it has executed inline scripts in head. And it refuses to execute
those scripts until the external CSS is downloaded, parsed and applied. You can
see the effect of this in this image, showing the request waterfall for
[[en:Gothic Alphabet]]: [2]. Notice how no images were requested before the
browser had finished processing the three load.php requests at the top.

To fix this, we want to move the inline scripts above the external CSS. This is
a little bit tricky, because the inline scripts depend on mw.loader, which is
loaded via an external script. If we move the external script so that it too is
above the external stylesheet, we force the browser to serialize requests,
because the browser will not retrieve the external CSS until it has retrieved
and executed the external JS code. So what we want is to move the inline
scripts above the external stylesheet, but keep the external script (which the
inline scripts depend on) below the external stylesheet.

We can do this by wrapping the inline script code in a closure (which binds mw
and $) and enqueuing the closure in a global array which will be processed by
the startup module at just the right time.

Net result: external CSS and JS is retrieved in parallel, retrieval of images
(and other external assets) is unblocked, but the order in which code is
evaluated remains the same.

[1]: <http://www.stevesouders.com/blog/2009/05/06/positioning-inline-scripts/>
[2]: http://people.wikimedia.org/~ori/enwiki-waterfall.png (excerpted from
 <http://www.webpagetest.org/result/150316_0C_7MB/1/details/>.

Change-Id: I98d383a6299ffbd10210431544a505338ca8643f
---
M includes/OutputPage.php
M includes/resourceloader/ResourceLoader.php
M includes/resourceloader/ResourceLoaderStartUpModule.php
M tests/phpunit/includes/OutputPageTest.php
4 files changed, 46 insertions(+), 44 deletions(-)


  git pull ssh://gerrit.wikimedia.org:29418/mediawiki/core 
refs/changes/89/196989/1

diff --git a/includes/OutputPage.php b/includes/OutputPage.php
index edeae0d..bc4b20c 100644
--- a/includes/OutputPage.php
+++ b/includes/OutputPage.php
@@ -2674,10 +2674,12 @@
                        $ret .= $item . "\n";
                }
 
+               $ret .= $this->getInlineHeadScript();
+
                // No newline after buildCssLinks since makeResourceLoaderLink 
did that already
                $ret .= $this->buildCssLinks();
 
-               $ret .= $this->getHeadScripts() . "\n";
+               $ret .= $this->getHeadScripts();
 
                foreach ( $this->mHeadItems as $item ) {
                        $ret .= $item . "\n";
@@ -2966,6 +2968,36 @@
        }
 
        /**
+        * Get <script> tags for <head> whose source is inline.
+        *
+        * @return string HTML fragment
+        */
+       function getInlineHeadScript() {
+               // Load config before anything else
+               $js = ResourceLoader::makeConfigSetScript( $this->getJSVars() );
+
+               // Construct mw.loader.load() call for top-loaded modules.
+               // Client-side code will request these modules and their 
dependencies.
+               $topModules = $this->getModules( true, 'top' );
+               if ( $topModules ) {
+                       $js .= Xml::encodeJsCall( 'mw.loader.load', array( 
$topModules ) );
+               }
+
+               $html = Html::inlineScript(
+                       ResourceLoader::makeLoaderConditionalScript( $js ) );
+
+               // Load embeddable private modules before any loader links
+               // This needs to be TYPE_COMBINED so these modules are properly 
wrapped
+               // in mw.loader.implement() calls and deferred until mw.user is 
available
+               $inlineModules = array( 'user.options', 'user.tokens' );
+               $inlineModulesLink = $this->makeResourceLoaderLink(
+                       $inlineModules, ResourceLoaderModule::TYPE_COMBINED );
+               $html .= "\n" . self::getHtmlFromLoaderLinks( array( 
$inlineModulesLink ) );
+
+               return $html;
+       }
+
+       /**
         * JS stuff to put in the "<head>". This is the startup module, config
         * vars and modules marked with position 'top'
         *
@@ -2975,19 +3007,6 @@
                // Startup - this will immediately load jquery and mediawiki 
modules
                $links = array();
                $links[] = $this->makeResourceLoaderLink( 'startup', 
ResourceLoaderModule::TYPE_SCRIPTS, true );
-
-               // Load config before anything else
-               $links[] = Html::inlineScript(
-                       ResourceLoader::makeLoaderConditionalScript(
-                               ResourceLoader::makeConfigSetScript( 
$this->getJSVars() )
-                       )
-               );
-
-               // Load embeddable private modules before any loader links
-               // This needs to be TYPE_COMBINED so these modules are properly 
wrapped
-               // in mw.loader.implement() calls and deferred until mw.user is 
available
-               $embedScripts = array( 'user.options', 'user.tokens' );
-               $links[] = $this->makeResourceLoaderLink( $embedScripts, 
ResourceLoaderModule::TYPE_COMBINED );
 
                // Scripts and messages "only" requests marked for top inclusion
                // Messages should go first
@@ -2999,17 +3018,6 @@
                        $this->getModuleScripts( true, 'top' ),
                        ResourceLoaderModule::TYPE_SCRIPTS
                );
-
-               // Modules requests - let the client calculate dependencies and 
batch requests as it likes
-               // Only load modules that have marked themselves for loading at 
the top
-               $modules = $this->getModules( true, 'top' );
-               if ( $modules ) {
-                       $links[] = Html::inlineScript(
-                               ResourceLoader::makeLoaderConditionalScript(
-                                       Xml::encodeJsCall( 'mw.loader.load', 
array( $modules ) )
-                               )
-                       );
-               }
 
                if ( $this->getConfig()->get( 
'ResourceLoaderExperimentalAsyncLoading' ) ) {
                        $links[] = $this->getScriptsForBottomQueue( true );
diff --git a/includes/resourceloader/ResourceLoader.php 
b/includes/resourceloader/ResourceLoader.php
index 5eab3cb..be3c84c 100644
--- a/includes/resourceloader/ResourceLoader.php
+++ b/includes/resourceloader/ResourceLoader.php
@@ -1330,7 +1330,8 @@
         * @return string
         */
        public static function makeLoaderConditionalScript( $script ) {
-               return "if(window.mw){\n" . trim( $script ) . "\n}";
+               $closure = 'function ( mw, $, jQuery ) { ' .  trim( $script ) . 
' }';
+               return '( window._mwq = window._mwq || [] ).push( ' . $closure 
. ' );';
        }
 
        /**
diff --git a/includes/resourceloader/ResourceLoaderStartUpModule.php 
b/includes/resourceloader/ResourceLoaderStartUpModule.php
index 48b3576..74d5c8b 100644
--- a/includes/resourceloader/ResourceLoaderStartUpModule.php
+++ b/includes/resourceloader/ResourceLoaderStartUpModule.php
@@ -357,11 +357,14 @@
                                ResourceLoader::inDebugMode()
                        );
 
+                       $mwqJs = 'if ( window._mwq ) while ( _mwq.length ) 
_mwq.shift()( mw, $, $ );';
+
                        $out .= "var startUp = function () {\n" .
                                "\tmw.config = new " .
                                $mwMapJsCall . "\n" .
                                "\t$registrations\n" .
-                               "\t" . $mwConfigSetJsCall .
+                               "\t" . $mwConfigSetJsCall . "\n" .
+                               "\t" . $mwqJs . "\n" .
                                "};\n";
 
                        // Conditional script injection
diff --git a/tests/phpunit/includes/OutputPageTest.php 
b/tests/phpunit/includes/OutputPageTest.php
index 77a572d..6b1db00 100644
--- a/tests/phpunit/includes/OutputPageTest.php
+++ b/tests/phpunit/includes/OutputPageTest.php
@@ -141,9 +141,7 @@
                        // Load module script only
                        array(
                                array( 'test.foo', 
ResourceLoaderModule::TYPE_SCRIPTS ),
-                               '<script>if(window.mw){
-document.write("\u003Cscript 
src=\"http://127.0.0.1:8080/w/load.php?debug=false\u0026amp;lang=en\u0026amp;modules=test.foo\u0026amp;only=scripts\u0026amp;skin=fallback\u0026amp;*\"\u003E\u003C/script\u003E";);
-}</script>
+                               '<script>( window._mwq = window._mwq || [] 
).push( function ( mw, $, jQuery ) { document.write("\u003Cscript 
src=\"http://127.0.0.1:8080/w/load.php?debug=false\u0026amp;lang=en\u0026amp;modules=test.foo\u0026amp;only=scripts\u0026amp;skin=fallback\u0026amp;*\"\u003E\u003C/script\u003E";);
 } );</script>
 '
                        ),
                        array(
@@ -162,19 +160,15 @@
                        // Load private module (only=scripts)
                        array(
                                array( 'test.quux', 
ResourceLoaderModule::TYPE_SCRIPTS ),
-                               '<script>if(window.mw){
-mw.test.baz({token:123});mw.loader.state({"test.quux":"ready"});
-
-}</script>
+                               '<script>( window._mwq = window._mwq || [] 
).push( function ( mw, $, jQuery ) { 
mw.test.baz({token:123});mw.loader.state({"test.quux":"ready"});
+ } );</script>
 '
                        ),
                        // Load private module (combined)
                        array(
                                array( 'test.quux', 
ResourceLoaderModule::TYPE_COMBINED ),
-                               '<script>if(window.mw){
-mw.loader.implement("test.quux",function($,jQuery){mw.test.baz({token:123});},{"css":[".mw-icon{transition:none}\n"]},{},{});
-
-}</script>
+                               '<script>( window._mwq = window._mwq || [] 
).push( function ( mw, $, jQuery ) { 
mw.loader.implement("test.quux",function($,jQuery){mw.test.baz({token:123});},{"css":[".mw-icon{transition:none}\n"]},{},{});
+ } );</script>
 '
                        ),
                        // Load module script with ESI
@@ -203,12 +197,8 @@
                        // Load two modules in separate groups
                        array(
                                array( array( 'test.group.foo', 
'test.group.bar' ), ResourceLoaderModule::TYPE_COMBINED ),
-                               '<script>if(window.mw){
-document.write("\u003Cscript 
src=\"http://127.0.0.1:8080/w/load.php?debug=false\u0026amp;lang=en\u0026amp;modules=test.group.bar\u0026amp;skin=fallback\u0026amp;*\"\u003E\u003C/script\u003E";);
-}</script>
-<script>if(window.mw){
-document.write("\u003Cscript 
src=\"http://127.0.0.1:8080/w/load.php?debug=false\u0026amp;lang=en\u0026amp;modules=test.group.foo\u0026amp;skin=fallback\u0026amp;*\"\u003E\u003C/script\u003E";);
-}</script>
+                               '<script>( window._mwq = window._mwq || [] 
).push( function ( mw, $, jQuery ) { document.write("\u003Cscript 
src=\"http://127.0.0.1:8080/w/load.php?debug=false\u0026amp;lang=en\u0026amp;modules=test.group.bar\u0026amp;skin=fallback\u0026amp;*\"\u003E\u003C/script\u003E";);
 } );</script>
+<script>( window._mwq = window._mwq || [] ).push( function ( mw, $, jQuery ) { 
document.write("\u003Cscript 
src=\"http://127.0.0.1:8080/w/load.php?debug=false\u0026amp;lang=en\u0026amp;modules=test.group.foo\u0026amp;skin=fallback\u0026amp;*\"\u003E\u003C/script\u003E";);
 } );</script>
 '
                        ),
                );

-- 
To view, visit https://gerrit.wikimedia.org/r/196989
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings

Gerrit-MessageType: newchange
Gerrit-Change-Id: I98d383a6299ffbd10210431544a505338ca8643f
Gerrit-PatchSet: 1
Gerrit-Project: mediawiki/core
Gerrit-Branch: master
Gerrit-Owner: Ori.livneh <[email protected]>

_______________________________________________
MediaWiki-commits mailing list
[email protected]
https://lists.wikimedia.org/mailman/listinfo/mediawiki-commits

Reply via email to