开发者

Deferring JavaScript loading

开发者 https://www.devze.com 2023-04-01 02:18 出处:网络
I have heard and read a few articles about deferring JavaScript loading and am very interested. It seems to be very promising for web apps that may be useful on Mobile platforms where the amount of Ja

I have heard and read a few articles about deferring JavaScript loading and am very interested. It seems to be very promising for web apps that may be useful on Mobile platforms where the amount of JavaScript that can be loaded and executed is limited.

Unfortunately, most of the articles talk about this at an extremely high level. How would one approach this?

EDIT

Normally, all JavaScript is loaded on page load, however, there may be functions that are not necessary until a certain action occurs, at which time, the JavaScript should be loaded. This helps ease the burden of the browser on page load.

Specifically, 开发者_如何学运维I have a page that very heavily uses JavaScript. When I load the page on my phone, it won't load properly. As I debugged the page, I eliminated some of the JS functions. Once enough was eliminated, the page suddenly worked.

I want to be able to load the JS as needed. And possibly even eliminate the functions simply used for start up.


The basics are simple - breaking up your JavaScript code into logically separate components and loading only what you need. Depending on what you are building you can use:

Loaders:

  • Modernizr.load (or yepnope.js by itself)
  • LABjs
  • Many, many, many other deferred loading libraries.

Dependency managers (which are also loaders):

  • Require.js
  • dojo.require
  • JavaScript MVC's steal.js
  • Several other dependency management libraries.

These tools make use of a wide variety of techniques to defer the loading of scripts, the execution of scripts, manage dependencies, etc. What you need depends on what you are building.

You may also want to read through this discussion to learn something more about the pros and cons of using such techniques.


Response to edit:

There isn't really a good way to unload JavaScript that you have already loaded - the closest approximation you can get is to keep all of your loading code namespaced inside your application's namespace and then "clean up" by setting that namespace, and all references to it to null.


I have used a simple script published on line with some modification done by me. Assume that your COMPRESSED Javascript file is in the cache directory in your webserver and you want to defer the loading of this compressed js file.

Your compressed js file:

80aaad2a95e397a9f6f64ac79c4b452f.js

This is the code html code:

<script type="text/javascript" src="/resources/js/defer.js?cache=80aaad2a95e397a9f6f64ac79c4b452f.js"></script>

This is the defer.js file content:

(function() {

    /*
     * http://gtmetrix.com/
     * In order to load a page, the browser must parse the contents of all <script> tags, 
     * which adds additional time to the page load. By minimizing the amount of JavaScript needed to render the page, 
     * and deferring parsing of unneeded JavaScript until it needs to be executed, 
     * you can reduce the initial load time of your page.
     */

    // http://feather.elektrum.org/book/src.html
    // Get the script tag from the html
    var scripts = document.getElementsByTagName('script');
    var myScript = scripts[ scripts.length - 1 ];

    // Get the querystring
    var queryString = myScript.src.replace(/^[^\?]+\??/,'');

    // Parse the parameters
    var params = parseQuery( queryString );

    var s = document.createElement('script');
    s.type = 'text/javascript';
    s.async = true;
    s.src = '/cache/' + params.cache; // Add the name of the js file 

    var x = document.getElementsByTagName('script')[0];
    x.parentNode.insertBefore(s, x);

    function parseQuery ( query ) {
       var Params = new Object ();
       if ( ! query ) return Params; // return empty object
       var Pairs = query.split(/[;&]/);
       for ( var i = 0; i < Pairs.length; i++ ) {
          var KeyVal = Pairs[i].split('=');
          if ( ! KeyVal || KeyVal.length != 2 ) continue;
          var key = unescape( KeyVal[0] );
          var val = unescape( KeyVal[1] );
          val = val.replace(/\+/g, ' ');
          Params[key] = val;
       }
       return Params;
    }
})();

I would like to say thanks to http://feather.elektrum.org/book/src.html that helped me to understand how to get the parameters from the script tag.

bye


Deferring loading til when? The reason typically why JS is loaded last, is so that the entire DOM has been loaded first.

An easy way is to just use

<body onload="doSomething();">

So you could easily have doSomething() function to load all your JS.

You can also add a function to window.onload, like

window.onload = function(){ };

Also, if you are using JS librarys, such as jQuery and Dojo, they each have their own onReady and addOnLoad methods in order to run some JS only after the document has already loaded.


Here's a useful article on the script element's defer and async attributes. Specifying these attributes will get the browser to defer loading in different ways. You can also load in an external script using JavaScript after page load.

It should also be noted that the position of your script elements within your HTML document will determine load and execution order if neither defer nor async have been specified.

0

精彩评论

暂无评论...
验证码 换一张
取 消