【问题标题】:Preload Images in JavaScript在 JavaScript 中预加载图像
【发布时间】:2014-03-23 21:59:50
【问题描述】:

我正在开发一个小游戏,你按下一个按钮就会出现一个新图像。每次您要求显示新图像时都会出现故障,我想到我应该预加载必要的图像。但是,我不确定如何有效地执行此操作,因为我没有使用变量来显示图像。 This 是我正在做的事情。有什么建议吗?

HTML:

<body onLoad="setup()">
<div id="wrapper">
        <div id="jajo"></div><!--this is where jajo will be displayed-->
        <div id="directions"></div><!--directions for how to interact with jajo-->
    </div><!--wrapper-->
</body>

JavaScript:

// Calls the loadJajo function and passes the image URL
// Initiates directionSlide function
function setup() {
loadJajo('jajo.png');
elem = document.getElementById('directions');
directionSlide();
}

//Creates a new image object (Jajo) and writes it to the page.
function loadJajo(jajoSRC) {
var main = document.getElementById('jajo'); // Creates an variable to represent the "main" division
var defaultJajo = document.createElement('img'); // Creates a new image object (default Jajo image)
defaultJajo.src = jajoSRC; // adds the source file name to the defaultJajo image object
main.appendChild(defaultJajo); //puts the defaultJajo object inside the "main" division
}

// Listen for key pressed events.
document.onkeydown = function(event) {
var keyPress = String.fromCharCode(event.keyCode); // Assigns value of key pressed to variable.

if(keyPress == "W") { // If 'W' is pressed, display Jajo waving.
    document.getElementById("jajo").innerHTML= "<img alt='car' src='jajo_wave.png'>";
    document.onkeyup = function(event) { // If 'W' is released, display default Jajo.
        document.getElementById("jajo").innerHTML= "<img alt='Jajo' src='jajo.png'>";
    }
} else if(keyPress == "A") { // If 'A' is pressed, display Jajo winking.
    document.getElementById("jajo").innerHTML= "<img alt='car' src='jajo_wink.png'>";
    document.onkeyup = function(event) { // If 'A' is released, display default Jajo.
        document.getElementById("jajo").innerHTML= "<img alt='Jajo' src='jajo.png'>";
    }
} else if(keyPress == "S") { // If 'S' is pressed, display transparent Jajo.
    document.getElementById("jajo").innerHTML= "<img alt='car' src='jajo_invisible.png'>";
    document.onkeyup = function(event) { // If 'S' is released, display default Jajo.
        document.getElementById("jajo").innerHTML= "<img alt='Jajo' src='jajo.png'>";
    }
} else if(keyPress == "D") { // If 'D' is pressed, display purple Jajo.
    document.getElementById("jajo").innerHTML= "<img alt='car' src='jajo_purple.png'>";
    document.onkeyup = function(event) { // If 'D' is released, display default Jajo.
        document.getElementById("jajo").innerHTML= "<img alt='Jajo' src='jajo.png'>";
    }
} else if(keyPress == "E") { // If 'E' is pressed, display Jajo eating a carrot.
    document.getElementById("jajo").innerHTML= "<img alt='car' src='jajo_carrot.png'>";
    document.onkeyup = function(event) { // If 'E' is released, display default Jajo.
        document.getElementById("jajo").innerHTML= "<img alt='Jajo' src='jajo.png'>";
    }
}
}

var elem;
var i = 0; // Counter variable.
// Array with directions for interacting with Jajo.
var directionArray = ["This is Jajo, your new pet monster!",
             "Jajo wants to say 'Hi!'<br>Press and hold 'W'",
             "Jajo has some special skills.<br>Press and hold 'D' to see one!",
             "Jajo is hungry for a healthy snack.<br>Press and hold 'E'",
             "Jajo wants to show you his secret power.<br>Press and hold 'S'",
             "That secret is just between you and Jajo!<br>Press and hold 'A'"];

// Transitions one direction to the next.
function nextDirection() {
i++; // Continuously add 1 to i.
elem.style.opacity = 0; // Directions opacity at 0%.
if(i > (directionArray.length - 1)) { // Resets counter to 0 when it reaches the end of the array.
    i = 0;
}
setTimeout(directionSlide,1000); // Set time delay for transition between directions.
}

// Displays direction one at a time.
// http://www.developphp.com/view.php?tid=1380
function directionSlide() {
elem.innerHTML = directionArray[i]; // Displays direction based on position of counter variable.
elem.style.opacity = 1; // Direction opacity at 100%.
setTimeout(nextDirection,5000); // Set time delay for display of directions.
}

【问题讨论】:

  • 属于codereview.SE

标签: javascript preload


【解决方案1】:

使用 JavaScript 预加载图像

将图像路径放在一个数组中,然后遍历该数组:

(function () {
    // All image paths go in this array
    var images = [ "jajo_wave.png", "jajo_wink.png" ];
    // Cycle over the array, pre-loading each image
    for ( var i = 0; i < images.length; i++ ) {
        // Create new image object
        var image = document.createElement( "img" );
        // For debugging, output successful preloading msg
        image.onload = function () {
            console.log( "Loaded: " + this.src );
        }
        // Set image source
        image.src = images[ i ];
    }
}());

但更重要的是......

正如comment above 中所述,您的代码应该进行相当多的重构。请务必通过https://codereview.stackexchange.com/ 进行代码审查。

您要解决的一个非常突出的问题是不断往返于 DOM 以查找相同的元素。存储对您的元素的引用,这样您就不必一直到处寻找它们。

【讨论】:

    【解决方案2】:

    我已经回答了一个类似的问题:

    https://stackoverflow.com/a/46121439/1951947

    在你的情况下是:

    <link rel="preload" href="bg-image-narrow.png" as="image" media="(max-width: 600px)">
    

    然后你可以在任何你喜欢的地方使用你的图像,它已经被缓存(预加载)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-08
      • 1970-01-01
      • 2014-02-02
      • 2023-03-18
      相关资源
      最近更新 更多