开发者

very simple javascript image load question

Very new to javascript here folks, so forgive the newbie question.

I want to load a very simple and small image with javascript. Can I do an that is triggered by an onload?

Note: The reason 开发者_如何学JAVAfor this is I have a section of a website that requires javascript to work properly. I want to have a little green circle to show a user that they have javascript installed.


Pretty simple (no need to import a library):

<!-- somewhere in your document's <body> tag -->
<div id="divId">

</div>

<!-- in your document's <head> tag, or a separate .js file -->
<script>
// addLoadEvent function for executing JavaScript on page load
// adds the event in such a way that any previously added onload functions 
// will be executed first.
function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

addLoadEvent(function() {
  document.getElementById('divId').innerHTML = "<img src='yourimage.gif' />"
  // add more code here if necessary
});



</script>


This code assumes that you don't use JQuery.

var preloadedImage;    

function PageIsLoaded(e)
{
    preloadedImage = new Image();
    img.src = 'pathToYourImage.jpg';
    // preloading
    img.onLoad = function () { displayImage() };
}

function displayImage()
{  
    // Assuming that this id refers to an IMG tag
    var imgHolder = document.getElementById('imgHolder');
    imgHolder = preloadedImage;
}


The most simple and easiest way to do this is using a javascript library, which utilizes load or ready functions. Example with jquery, launches, when document is ready :)

$(function () {
    $('body').append('<img src="/img/js-is-working.jpg" />');
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜