Adam Storr
Adam Storr

Reputation: 1450

JS Bookmarklet -- Script won't run on some sites

I'm creating a bookmarklet that works great on some sites, but not at all on others. When it fails, the script is still added to the bottom... but only part of the javascript runs.

I'm assuming there are javascript conflicts... thoughts? I've noticed that I works least on sites that already have jQuery.

The code is below. Thanks!

if (!($ = window.jQuery)) {
    alert('no jquery! its being added');
    script = document.createElement( 'script' );
    script.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js';
    script.onload=runEverything;
    document.body.appendChild(script);
} else {
    alert('jquery exists!');
    runEverything();
}

Upvotes: 0

Views: 194

Answers (1)

Emre Erkan
Emre Erkan

Reputation: 8482

This should work.

if (!($ == window.jQuery)) {
    alert('no jquery! its being added');
    script = document.createElement( 'script' );
    script.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js';
    script.onload=runEverything;
    document.body.appendChild(script);
} else {
    alert('jquery exists!');
    runEverything();
}

Althought I recommend this;

if (typeof jQuery == 'undefined') {
    alert('no jquery! its being added');
    script = document.createElement( 'script' );
    script.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js';
    script.onload=runEverything;
    document.body.appendChild(script);
} else {
    alert('jquery exists!');
    runEverything();
}

Upvotes: 2

Related Questions