加载脚本异步 [英] load scripts asynchronously

查看:96
本文介绍了加载脚本异步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用的几个插件,用户控件和JQuery的一些其他库。作为一个结果,我有几个的.js和.css文件。我需要的,因为它需要一些时间来加载,以创建一个装载机为我的网站。这将是很好,如果我可以在导入前显示加载所有的:

I am using several plugins, custom widgets and some other libraries from JQuery. as a result I have several .js and .css files. I need to create a loader for my site because it takes some time to load. it will be nice if I can display the loader before importing all the:

<script type="text/javascript" src="js/jquery-1.6.2.min.js"></script>
<script type="text/javascript" src="js/myFunctions.js"></script>
<link type="text/css" href="css/main.css" rel="stylesheet" />
... 
....
 etc

我已经发现了几个教程,使我以异步方式导入JavaScript库。例如,我可以这样做:

I have found several tutorials that enable me to import a JavaScript library asynchronously. for example I can do something like:

  (function () {
        var s = document.createElement('script');
        s.type = 'text/javascript';
        s.async = true;
        s.src = 'js/jquery-ui-1.8.16.custom.min.js';
        var x = document.getElementsByTagName('script')[0];
        x.parentNode.insertBefore(s, x);
    })();

因为当我做同样的事情,我的所有文件的网页不工作的一些原因。我一直在努力了这么久,试图找到问题所在,但我无法找到它。首先,我认为这可能是因为一些JavaScript函数依赖于他人。但我装他们使用的超时功能以正确的顺序,当一个完成我继续下一个和页面仍行为怪异。例如我不能点击链接等...动画仍然可以工作,但..

for some reason when I do the same thing for all my files the pages does not work. I have been trying for so long to try to find where the problem is but I just cannot find it. First I thought that it was probably because some javascript functions depended on the others. but I loaded them in the right order using the time out function when one completed I proceeded with the next and the page still behaves weird. for example I am not able to click on links etc... animations still work though..

下面就是我一直在想......我认为浏览器有一个缓存就是为什么它需要很长的时间来加载页面的第一次,下一次它是快速的。所以我在想什么做的是一个页面,该页面异步加载所有这些文件替换我的index.html页面。当AJAX加载完成所有这些文件重定向到我计划使用的页面。使用该网页时,它不应该采取长加载由于文件应该alredy被包括在浏览器的缓存中。在我的索引页(页,在这里的.js和.css文件获得异步加载)我不在乎得到错误的。完成后我将只是显示加载器,重定向的页​​面...

Here is what I have been thinking... I believe browsers have a cache that's why it takes a long time to load the page for the first time and the next time it is quick. so what I am thinking of doing is replacing my index.html page with a page that loads all this files asynchronously. when ajax is done loading all those files redirect to the page that I plan on using. when using that page it should not take long to load since the files should alredy be included on the cache of the browser. on my index page (page where .js and .css file get loaded asynchronously) I don't care of getting errors. I will just be displaying a loader and redirecting the page when done...

这种想法一个很好的选择?或者我应该不断尝试在执行异步方法?

Is this idea a good alternative? or should I keep trying on implementing the asynchronously methods?

我加载的一切异步是喜欢的方式:

the way I load everything async is like:

importScripts();

function importScripts()
{
    //import: jquery-ui-1.8.16.custom.min.js
    getContent("js/jquery-1.6.2.min.js",function (code) {
                var s = document.createElement('script');
                s.type = 'text/javascript';
                //s.async = true;
                s.innerHTML=code;
                var x = document.getElementsByTagName('script')[0];
                x.parentNode.insertBefore(s, x);
                setTimeout(insertNext1,1);
            });


    //import: jquery-ui-1.8.16.custom.min.js
    function insertNext1()
    {
        getContent("js/jquery-ui-1.8.16.custom.min.js",function (code) {
                    var s = document.createElement('script');
                    s.type = 'text/javascript';
                    s.innerHTML=code;
                    var x = document.getElementsByTagName('script')[0];
                    x.parentNode.insertBefore(s, x);
                    setTimeout(insertNext2,1);
                });
    }

    //import: jquery-ui-1.8.16.custom.css
    function insertNext2()
    {

        getContent("css/custom-theme/jquery-ui-1.8.16.custom.css",function (code) {
                    var s = document.createElement('link');
                    s.type = 'text/css';
                    s.rel ="stylesheet";
                    s.innerHTML=code;
                    var x = document.getElementsByTagName('script')[0];
                    x.parentNode.insertBefore(s, x);
                    setTimeout(insertNext3,1);
                });
    }

    //import: main.css
    function insertNext3()
    {

        getContent("css/main.css",function (code) {
                    var s = document.createElement('link');
                    s.type = 'text/css';
                    s.rel ="stylesheet";
                    s.innerHTML=code;
                    var x = document.getElementsByTagName('script')[0];
                    x.parentNode.insertBefore(s, x);
                    setTimeout(insertNext4,1);
                });
    }

    //import: jquery.imgpreload.min.js
    function insertNext4()
    {
        getContent("js/farinspace/jquery.imgpreload.min.js",function (code) {
                    var s = document.createElement('script');
                    s.type = 'text/javascript';
                    s.innerHTML=code;
                    var x = document.getElementsByTagName('script')[0];
                    x.parentNode.insertBefore(s, x);
                    setTimeout(insertNext5,1);
                });
    }


    //import: marquee.js
    function insertNext5()
    {
        getContent("js/marquee.js",function (code) {
                    var s = document.createElement('script');
                    s.type = 'text/javascript';
                    s.innerHTML=code;
                    var x = document.getElementsByTagName('script')[0];
                    x.parentNode.insertBefore(s, x);
                    setTimeout(insertNext6,1);
                });
    }


    //import: marquee.css
    function insertNext6()
    {

        getContent("css/marquee.css",function (code) {
                    var s = document.createElement('link');
                    s.type = 'text/css';
                    s.rel ="stylesheet";
                    s.innerHTML=code;
                    var x = document.getElementsByTagName('script')[0];
                    x.parentNode.insertBefore(s, x);
                    setTimeout(insertNext,1);
                });
    }



    function insertNext()
    {
        setTimeout(pageReadyMan,10);        
    }
}


// get the content of url and pass that content to specified function
function getContent( url, callBackFunction )
{
     // attempt to create the XMLHttpRequest and make the request
     try
     {
        var asyncRequest; // variable to hold XMLHttpRequest object
        asyncRequest = new XMLHttpRequest(); // create request object

        // register event handler
        asyncRequest.onreadystatechange = function(){
            stateChange(asyncRequest, callBackFunction);
        } 
        asyncRequest.open( 'GET', url, true ); // prepare the request
        asyncRequest.send( null ); // send the request
     } // end try
     catch ( exception )
     {
        alert( 'Request failed.' );
     } // end catch
} // end function getContent

// call function whith content when ready
function stateChange(asyncRequest, callBackFunction)
{
     if ( asyncRequest.readyState == 4 && asyncRequest.status == 200 )
     {
           callBackFunction(asyncRequest.responseText);
     } // end if
} // end function stateChange

和怪异的是,所有样式的工作加上所有的JavaScript函数。该页面被冻结出于某种原因,虽然...

and the weird part is that all the style's work plus all the javascript functions. the page is frozen for some reason though...

推荐答案

对于异步加载一对夫妇的解决方案:

A couple solutions for async loading:

//this function will work cross-browser for loading scripts asynchronously
function loadScript(src, callback)
{
  var s,
      r,
      t;
  r = false;
  s = document.createElement('script');
  s.type = 'text/javascript';
  s.src = src;
  s.onload = s.onreadystatechange = function() {
    //console.log( this.readyState ); //uncomment this line to see which ready states are called.
    if ( !r && (!this.readyState || this.readyState == 'complete') )
    {
      r = true;
      callback();
    }
  };
  t = document.getElementsByTagName('script')[0];
  t.parentNode.insertBefore(s, t);
}

如果你已经有jQuery的页面上,只需使用

If you've already got jQuery on the page, just use

$。getScript加入脚本(URL,successCallback)

此外,它可能已被加载脚本/执行文件加载完成前,这意味着你需要之前的事件可以等待的document.ready 被绑定到元素

Additionally, it's possible that your scripts are being loaded/executed before the document is done loading, meaning that you'd need to wait for document.ready before events can be bound to the elements.

这是不可能告诉你的问题具体是什么没有看到code。

It's not possible to tell specifically what your issue is without seeing the code.

最简单的解决办法是让所有的脚本内嵌在页面的底部,这样,他们不会阻止HTML内容的加载,而他们执行。这也避免了异步加载每个所需的脚本的问题。

The simplest solution is to keep all of your scripts inline at the bottom of the page, that way they don't block the loading of HTML content while they execute. It also avoids the issue of having to asynchronously load each required script.

如果您有没有经常使用,需要某种形式的大剧本特别看中的相互作用,也可能直到它需要的是有用的,以避免加载特定的脚本(延迟加载)。

If you have a particularly fancy interaction that isn't always used that requires a larger script of some sort, it could be useful to avoid loading that particular script until it's needed (lazy loading).

对于任何人谁可以使用现代化的功能,如<一个href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise"><$c$c>Promise对象时,<​​code> loadScript 功能已经成为显著简单:

For anyone who can use modern features such as the Promise object, the loadScript function has become significantly simpler:

function loadScript(src) {
    return new Promise(function (resolve, reject) {
        var s;
        s = document.createElement('script');
        s.src = src;
        s.onload = resolve;
        s.onerror = reject;
        document.head.appendChild(s);
    });
}

请注意,此版本不再接受回调参数作为返回的承诺将处理回调。什么previously本来 loadScript(SRC,回调)现在将 loadScript(SRC)。然后(回调)

Be aware that this version no longer accepts a callback argument as the returned promise will handle callback. What previously would have been loadScript(src, callback) would now be loadScript(src).then(callback).

这具有能够检测和处理故障,增加的奖金例如,一个可以称之为......

This has the added bonus of being able to detect and handle failures, for example one could call...

loadScript(cdnSource)
    .catch(loadScript.bind(null, localSource))
    .then(successCallback, failureCallback);

...并会妥善处理CDN停运。

...and it would handle CDN outages gracefully.

这篇关于加载脚本异步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆