$.getScript() and $(window).load() in Safari 5 not always working
I'm experiencing a similar problem to this guy except my problem is related to scripts and not images.
I'm using a combination of $.getScript()
and $(window).load()
to load JavaScript dynamically and use functions that are being loaded once the script has completely finished loading.
It works well in 开发者_如何学CChrome but Safari seems to always fire the onload
event too early. I was wondering if there was some way to force Safari to wait for all scripts to load similarly to the document.body.offsetWidth
block. From what I understood (and from the results I saw when I tested it), document.body.offsetWidth
blocks until styles and images are loaded but apparently not scripts.
Edit: It might be worth mentioning that it does work in Safari sometimes but I don't see a pattern. Sometimes the event is fired before the script is fully loaded and executed and the handler passed $(window).load()
fails because the functions are missing.
Based on the comments you have made, specifically those surrounding dependencies, I would use a library like RequireJS. This will give you what you need to import scripts and their dependencies, and also hooks to call functions and code when dependencies are met.
Have you tried the good old document ready?
$(document).ready(function() {
//code here
})
I've never had any issues when using that. Worst case scenario, you can drop a script tag after all your other script tags that include the code you require.
In this example, I tell loaded scripts that I need to do something to report loaded to a function. Once all that I need are loaded, I run whatever code I need to.
// Simplified callback to check for all scrips loaded.
var numDynScriptsReady = 0,
numDynScriptsNeeded = 4;
function dynScriptsReady()
{
numDynScriptsReady++;
if( numDynScriptsLoaded == numDynScriptsNeeded )
{
// Run functions you need after loaded....
}
}
// Example script get
$.getScript( "http://example.com/script.js", dynScriptsReady );
// etc....
精彩评论