I have a webpage created by a php script that upon loading will contain 0 to N div elements. For each div I run a specific javascript code that manipulates data relevant to that div. One of the things this code does is create an img element and set its 'src' attribute to a certain url of an image of a known (but variable) size. This is done for caching. Those images are not supposed to be displayed in the initial page layout - but each should appear after a certain user input (mouse h开发者_开发百科over) - so I'm trying to cache the images so it won't take long for them to appear.
The loading of the images of-course takes time - and each time an image loads the code blocks resulting in high load times. an example:
<div id="i1">
<script type="text/javascript">
/* run code relevant to 'i1', and amongst other things load some image
into a detached img element for later use. let's call this code 'bcode' */
</script>
<div id="i2">
<script type="text/javascript">
/* run 'bcode' for i2 */
</script>
<div id="...and so on">
To try having the code run asynchronously, I tried this:
<div id="i1">
(function() {
var asyncScriptElement = document.createElement('script');
asyncScriptElement.async = true;
var scriptText = document.createTextNode ('here I put all of the relevant "bcode"');
asyncScriptElement.appendChild (scriptText);
document.getElementById ('Img_1_2').appendChild (asyncScriptElement);
}());
It works under FF (still not fast enough), and it obviously doesn't work under IE. Do you have any suggestion as to how to achieve this? Also note, that I don't really need to get anything from another external php (i.e. to use XMLHttpRequest) - I got all the data I need in this php. I just need a way to make the loading of the images unblocking...
Looks like you need the waitfor/and construct provided by the apollo library: http://onilabs.com/stratifiedjs#waitfor-and
Javascript is single threaded and always runs synchronously.
There are browser extensions to get around this, notably the concept of Javascript Workers in Mozilla
I would wrap your scripts in an HTML page (eventually generated by PHP) and download it as an iframe to assure the same behaviour for any browser.
There are other more elegant options with pros and cons; here you can find a comparison of viable options, browser compatibility and a nice decision tree.
精彩评论