Delaying a jquery script until everything else has loaded

后端 未结 6 789
旧巷少年郎
旧巷少年郎 2020-11-29 18:49

I have a jquery script which I need to run only once everything else on the page, including some other javascripts (over which I have no control) have finished doing their t

6条回答
  •  误落风尘
    2020-11-29 19:16

    From here:

    // Add jQuery 
    var GM_JQ = document.createElement('script'); 
    GM_JQ.src = 'http://jquery.com/src/jquery-latest.js';
    GM_JQ.type = 'text/javascript'; 
    document.getElementsByTagName('head')[0].appendChild(GM_JQ); 
    
    // Check if jQuery's loaded 
    function GM_wait() 
    { 
        if(typeof unsafeWindow.jQuery == 'undefined') 
        { 
            window.setTimeout(GM_wait,100); 
        } 
        else 
        { 
            $ = unsafeWindow.jQuery; 
            letsJQuery(); 
        } 
    } 
    
    GM_wait(); 
    
    // All your GM code must be inside this function 
    function letsJQuery() 
    {
        // Do your jQuery stuff in here    
    } 
    

    This will wait until jQuery is loaded to use it, but you can use the same concept, setting variables in your other scripts (or checking them if they're not your script) to wait until they're loaded to use them.

    For example, on my site, I use this for asynchronous JS loading and waiting until they're finished before doing anything with them using jQuery:

     
    

提交回复
热议问题