繁体   English   中英

强制某些JS文件和图像在包括JS文件在内的任何其他内容之前加载

[英]Forcing certain JS files and images to load before anything else including JS files

因为我的客户端页面有大量的Javascript,我在移动版本顶部添加的图像轮播需要永远在智能手机上呈现。 我想加载轮播图像然后轮播所需的文件(jQuery,carousel JS文件,carousell CSS文件)之前的任何其他包括JS,CSS等。

是否有可能,如果可以的话怎么做?

试试这种方式:
从javascript加载图片

如果你可以先加载图像,然后只是在任何地方使用它,它们会在javascript加载后立即加载,你必须将这个javascript放在其他所有内容之前(正如你的要求)

并且,要首先加载JS,您只需将它们作为第一个,例如:

必须引导程序之前加载JQuery,否则它将无法运行。

您可以创建一个javascript方法来检查所有图像是否已加载。

var preLoadImages = function (arr) {
    var newImages = [], // temparary variable containing loaded images
        loadedImagesCount = 0; // 
    var postAction = function () {};
    var arr = (typeof arr != "object") ? [arr] : arr; // if a single image is sent, convert it into array

    function imageLoadPost() {
        loadedImagesCount++;
        if (loadedImagesCount == arr.length) {
            postAction(newImages) // postAction method
        }
    }
    for (var i = 0; i < arr.length; i++) {
        newImages[i] = new Image();
        newImages[i].src = arr[i];
        newImages[i].onload = function () { // call imageLoadPost when image is loaded
            imageLoadPost();
        }
        newImages[i].onerror = function () { // call imageLoadPost when error occurred because its also an success event which already checked whether mage is available or not
            imageLoadPost();
        }
    }
    return { //return blank object with done() method
        done: function (f) {
            postAction = f || postAction // user defined callback method to be called when all images are loaded
        }
    }
}

// image array contains all images which you want to preload - currently having sample images
var imgArr = ['http://doc.jsfiddle.net/_images/jsfiddle-logo-thumb.png', 'http://doc.jsfiddle.net/_images/jsfiddle-desktop-thumbnail-a.png'];
preLoadImages(imgArr).done(function (imgArr) {
    alert('all images loaded');
    // call your carousel here
})

在完成方法中,您可以创建您的轮播。 您需要在文件中添加此方法,并将其放在堆栈顶部,您可以在其中加载javascript文件。

JSFiddle链接

我有个主意:

  1. 首先加载jQuery。 [添加]

  2. 不要包含您想要延迟加载的js和css文件。

  3. 为你想要延迟加载的js和css编写一个javascript数组(按顺序)(见下文)。

  4. 在html中用属性标识你想要加载的所有内容。(只需使用任意的attr)

     <img src="_images/loadMeFirst.jpg" /> <img src="_images/1x1.png" lazyLoad="_images/loadMeLater.jpg" /> 
  5. 在文档完成后,浏览所有lazyLoad图像,使用lazyload src重新分配src attr。

  6. 在dom ready上,添加一个任意窗口事件监听器,也许是“LoadNextScript”,它将从数组中注入下一个。

  7. 在每个注入的js文件的末尾,添加一行来引发(任意)“LoadNextScript”事件。 (注意:如果您可以异步加载脚本,可以跳过此功能,只需像css文件一样加载它们。)

     $(window).trigger( "LoadNextScript" ); 
  8. 在文档完成后,引发第一个(任意)“LoadNextScript”事件。

  9. 在文档完成时,从css数组中注入css文件。

JS:

window.lazyLoad = {
    jsNextIndex: 0,
    jsFiles: ["_js/file1.js", "_js/file2.js"],
    cssFiles: ["_css/file1.css", "_css/file2.css"],
    loadLazyImages: function () {
        $('img[lazyLoad]').each(function () {
            var $img = $(this);
            $img.attr('src', $img.attr('lazyLoad'));
        });
    },
    loadNextScript: function () {
        // must add
        // $(window).trigger( "LoadNextScript" );
        // at the end of each js file to be lazy loaded.
        var sScriptSrc = window.lazyLoad.jsFiles[window.lazyLoad.jsNextIndex] || false;
        if (sScriptSrc) {
            $('<script type="text/javascript" src="' + sScriptSrc + '" />').appendTo($('body'));
        }
        window.lazyLoad.jsNextIndex++;
    },
    loadAllCss: function () {
        var $head = $('head');
        for (var i = 0; i < window.lazyLoad.cssFiles.length; i++) {
            $('<link rel="stylesheet" href="' + window.lazyLoad.cssFiles[i] + '" type="text/css" media="screen" />');
        }
    },
    domReady: function () {
        // wire Lazy Script Event
        $(window).bind('LoadNextScript', window.lazyLoad.loadNextScript);

        // on window load complete (all non-lazy images)
        $(window).load(function () {
            // load all lazy images
            window.lazyLoad.loadLazyImages();
            // load the css
            window.lazyLoad.loadAllCss();
            // load/trigger the first script
            window.lazyLoad.loadNextScript();
        });
    }
};

jQuery(function ($) {
    // init lazy loader
    window.lazyLoad.domReady();
});

使用<script async="true" src="zyx.js" />并将JS移动到页面底部。

假设你不得不解决你的客户端JS首先被加载而没有实现 优雅的 解决方案这一事实 - 你总是可以选择简单的解决方案并将async属性添加到慢速脚本中。

这是一个例子

如果您无法做到这一点 - 最好知道由于现有代码库的限制(例如,您可以移动script标记)。

如果你在旋转木马上对所有图像进行ajax加载,那么考虑使用本质上是async $.post

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM