How to determine if jQuery is fully initialized?

I am writing a bookmarklet using jQuery. It looks like javascript:document.write('<script src="path/to/loader.js"></script>'), and loader.jsperforms initialization:

check_the_environment();

document.head.innerHTML='<meta charset=utf-8>';
document.body.innerHTML='(the webpage)';

var jq=document.createElement('script');
jq.src='path/to/jquery.min.js';
document.head.appendChild(jq);

function load_core() {
    if(window.$)
        eval('(core js code)');
    else
      setTimeout(load_core,50);
}
load_core();

The loader loads the main javascript code after jQuery is available.

But sometimes I get this error in my main code:

$(...).on is not a function

It seems that jQuery was still initializing, although the value of the variable is $set.

So, I need to wait until jQuery is fully initialized before the loader loads the main code. How can i do this?

The traditional way of using is $(document).ready(...)not feasible, since jQuery loads after the web page is ready.

The following is the minimum Python code to test the health of a solution:

import cherrypy

mod='''
var htmlroot=document.getElementsByTagName('html')[0];

function load_core() {
  if(window.jQuery)
    jQuery(function(){
        alert($(document).on);
    });
  else
    setTimeout(load_core,10);
}

if(!document.head)
  htmlroot.appendChild(document.createElement('head'));

var jquery=document.createElement('script');
jquery.src='http://libs.useso.com/js/jquery/2.1.1/jquery.min.js';
document.head.appendChild(jquery);

load_core();
'''

class Website:
    @cherrypy.expose()
    def mod(self,_time):
        return mod

    @cherrypy.expose()
    def index(self):
        return '''<a href="javascript:document.write('<script src=/mod/'+(+new Date())+' ></script>')">Mod</a>'''

cherrypy.quickstart(Website(),'/');
+4
2

:

jQuery(function(){
    // code
});

jQuery noConflict, $ var .

$ var jQuery.

jQuery(function($){
    // you can use $ without worrying about conflicts now
});
+2

$

if(typeof $ == "function"){
    //Jquery loaded
}
0

Source: https://habr.com/ru/post/1619846/


All Articles