Preload javascript and css files

做~自己de王妃 提交于 2019-12-10 22:07:24

问题


I'm currently developing a mobile website which is heavy on the images, css and javascript (it uses a library which is 150KB uncompressed for example). I've constructed a preloader for the images which works rather nicely:

function loadImages(images){
    var sum = 0;
    for(i in images){
        sum += images[i][1]; // file size
    }
    setMaxProgress(sum);
    for(i in imageArray){
        var img = new Image();
        img.onload = function(){ addProgress(imageArray[i][1]); };
        img.src = imageArray[i][0];
    }
}

However I would now like to do something similar for the javascript and css, but there are a lot less resources available to do that. The only way I've found is to document.write() the html tags after the document is loaded but this doesn't hive me a (reliable) indication of when the files are loaded.

Is there a way to do this while I can still measure progress?

BTW: I use this as an addition to normale optimizing techniques like minifying js/css, gzipping, css sprites and proper cache control, not as a replacement. Users can skip loading and the site works perfectly fine then, albeit less smoothly


回答1:


If you need to know when JS is loaded use the following loadScript function. You might be able to do similarly for CSS, but I haven't tried it:

function preload(src, callback, node)
{
  var script,
      ready,
      where;

  where = node || document.body;
  ready = false;
  script = where.ownerDocument.createElement('script');
  script.src = src;
  script.onload=script.onreadystatechange=function(){
    if ( !ready && ( !this.readyState || this.readyState == 'complete' ) )
    {
      ready = true;
      callback();
      script.parentNode.removeChild(script);
    }
  };
  where.appendChild(script);
}

I've updated the function, and tested it in firefox. It works for both js and css (some cross-browser checking is required for css.

I'd also like to add a bit more information as to why you'd use the script element to preload css instead of a link element.

When the page is being loaded, resources that affect the structure of the DOM need to be analyzed and inserted in the order that they appear. Script elements need to be executed in the context of the partially loaded DOM so that they affect only existing DOM nodes.

Stylesheets included via link elements don't change the DOM (ignoring possible javascript insertion via url). It doesn't matter if the stylesheet is loaded before during or after the DOM tree is parsed, so there's no necessary callback as to when the resource is loaded. If a script element is used to link to a stylesheet, the external resource still needs to be loaded before the javascript interpreter can decide whether to perform any actions, or whether it should crash with an exception.

If you preload each script in the context of a hidden iframe, you can contain all the errors to a separate context without crashing javascript running on the page.

One word of caution: external scripts that perform functions will still have a chance to execute before being removed. If the script is performing ajax polling or similarly unnecessary actions, consider not pre-loading that particular script.

You may be able to get around this using 'loaded' in the place of 'complete', however there are some older browsers that only support onload, so for those browsers the scripts would still be executed. Pre-loading is really meant to be used for library components that need to be called on various different pages.




回答2:


"The only way I've found is to document.write() the html tags after the document is loaded but this doesn't hive me a (reliable) indication of when the files are loaded"

You could append script elements i.e in your head tag and attach handlers to the onload or onreadystatechange 'events' to have an indication of when the files are loaded.

Following url explains some things in detail:

http://unixpapa.com/js/dyna.html




回答3:


After the question was answered I came onto the following: in HTML5 the tag now has an async option and recently major browsers also began to implement the defer attribute (it has been in IE for a long time). You can also place the scripts on the bottom of your body.

These allow you to defer loading/execution of the script until after the page has loaded and thus effectively get the desired behaviour.

HTML5 also defines the onload property for script elements (tags) which is probably what makes the




回答4:


I did it this Way:

$('<link/>', {
  rel:'stylesheet',
  type:'text/css',
  href: => path goes here <=,
  media:'all'
}).appendTo('head');

Just enter your path there.

voilà.

(works perfect for me)

[edit] of course, you need Jquery




回答5:


An $import.js is a tiny utility, that allows to control js/css/less files loading to the document when only it's necessary.

Usage example:

$import("script.js", "style.css", "[:js]script.php", function(files){ console.log(files); });


来源:https://stackoverflow.com/questions/6806849/preload-javascript-and-css-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!