Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.
Use Selenium’s execute_async_script() to add a script element to the current page, then wait for its load or error event before calling jQuery. The example below checks for an existing window.jQuery, loads a version-pinned copy only if needed, and raises an error if the load fails.
Inject jQuery and wait for it to load
This Python example uses Selenium’s asynchronous JavaScript execution to wait for the browser’s script-loading event. It requests jQuery 4.0.0 from the jQuery CDN. The pattern applies Selenium’s documented script-execution interface and jQuery’s documented CDN approach; it was not executed as part of this article, so verify it in the browser and environment you use.
from selenium import webdriver
JQUERY_URL = "https://code.jquery.com/jquery-4.0.0.min.js"
# Assumes a working Chrome WebDriver setup and Selenium are installed.
driver = webdriver.Chrome()
try:
driver.get("https://example.com")
already_loaded = driver.execute_script(
"return typeof window.jQuery !== 'undefined'"
)
if not already_loaded:
driver.set_script_timeout(15)
loaded = driver.execute_async_script("""
const url = arguments[0];
const done = arguments[arguments.length - 1];
const script = document.createElement('script');
script.src = url;
script.onload = () => done(true);
script.onerror = () => done(false);
(document.head || document.documentElement).appendChild(script);
""", JQUERY_URL)
if not loaded:
raise RuntimeError("Could not load jQuery")
# Use window.jQuery rather than assuming '$' is available.
result = driver.execute_script(
"return window.jQuery('body').length"
)
print(result)
finally:
driver.quit()
Install Selenium and configure a browser driver before running the example. The try/finally ensures the browser is closed even if navigation, loading, or the subsequent page operation raises an exception. Replace https://example.com with the page you need to inspect.
Why use asynchronous execution?
execute_script() runs JavaScript in the current browsing context and returns when that script finishes. Adding a remote script element starts a network request, but the JavaScript that created it does not wait for the download. If you call jQuery immediately afterward, it may not exist yet.
#1 Best Overall
execute_async_script() gives the page a completion callback. The example passes Selenium’s callback as done, then calls it from the script element’s load or error handler. Selenium waits for that callback, subject to the script timeout. This makes success or failure explicit rather than relying on a guessed delay.
What the guard and return value do
The first check asks whether window.jQuery is already defined. If the target page has loaded jQuery itself, the code avoids injecting another copy. After a successful load—or when jQuery was already present—the example asks jQuery for the body and returns the number of matches. A value of 1 indicates that the selector matched one body element; this is only a simple demonstration that the library can be called, not a test of a more complex page operation.
Use window.jQuery when you want to call the library without assuming the short $ alias belongs to it. A page can call jQuery’s noConflict() or assign $ to another library, leaving window.jQuery available while $ is not.
Quick wins for a faster PC:
Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Clear out junk files and repair common Windows errorsFree Scan →Rank #2
Choose a jQuery version and build deliberately
As of September 29, 2026, the official jQuery CDN listing identifies 4.0.0 as the latest stable 4.x release and 3.7.1 as the latest stable 3.x release. jQuery announced 4.0.0 in January 2026; its release notes describe breaking changes and state that support for IE 10 and older was removed. For new automation, use 4.0.0 if its browser support and API changes suit the page. If you are reproducing behavior on a legacy site or existing automation depends on older APIs, consult the official upgrade guide and pin the particular version you need rather than silently switching versions.
The jQuery 3.x branch receives critical security patches and bug fixes, while 4.x is the current branch; older versions are no longer generally supported. Treat that as version guidance, not a guarantee that a particular site’s scripts are compatible. The page under test may have dependencies that constrain the version you can inject.
Full build or slim build?
The example uses the full minified 4.0.0 file. The slim build is smaller, but excludes Ajax and effects modules. Use it only if your page operation does not need those features; choose the full build when it does. Pinning an explicit URL makes the requested version clear and repeatable.
The official jQuery download documentation describes referencing the CDN file directly from a script tag and explains Subresource Integrity (SRI). If you add SRI to a dynamically created element, use the integrity value published for the exact file and configure the element as required by the CDN instructions. Do not copy an integrity value from a different version or build.
Run the script in the right page context
Selenium executes JavaScript in the current window or frame. If the content you need is inside an iframe, switch into that frame before checking for jQuery or injecting it; otherwise the script runs against the parent document, not the iframe’s document. Switch back to the parent context when you are finished if later steps need it.
# Example: switch to an iframe found by its name or locator.
frame = driver.find_element("css selector", "iframe")
driver.switch_to.frame(frame)
# Check or inject jQuery here; the code runs in this frame.
# Return to the parent document when done.
driver.switch_to.default_content()
Injection changes the currently loaded document. After a navigation, or when you switch to another frame or window, check the relevant context again rather than assuming the library carried over. A fresh document has its own JavaScript environment.
Or skip the browser setup
If your goal is a page image or PDF rather than running jQuery against the live DOM, ScreenshotNeo can capture a URL with one API request. See the ScreenshotNeo API documentation for request options.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://example.com -o shot.webp
ScreenshotNeo accepts cookie and consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; those steps can be turned off. Bot checks, blank pages, timeouts, failed loads, and cache hits cost nothing, and response headers identify the page verdict and whether the request was billed. Its MCP server gives AI agents tools for screenshots, page information, and PDF capture. The Free plan includes 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots. For this kind of visual capture, those features can avoid setting up and maintaining a browser script; they do not inject jQuery or replace Selenium when you need to execute page logic. Learn more at ScreenshotNeo, or sign up for 1,000 free screenshots a month with no card.
Do these 3 things before closing this tab:
1Clear out junk files and repair common Windows errors2Scan for outdated or missing drivers - takes under a minute3Repair Windows errors before they cause bigger problemsTroubleshoot common failures
The script times out
A timeout means Selenium did not receive the asynchronous completion callback within the configured script timeout. In this example, the timeout is 15 seconds. Check whether the page is still loading, whether the CDN request is stalled, and whether the browser reports a blocked or failed script request. Increase the timeout only when slower loading is expected; a longer timeout does not fix a blocked URL or an unreachable CDN.
The load handler reports failure
The script element’s error handler calls done(false), which leads to the RuntimeError. Inspect the browser’s network and console diagnostics for the failed resource. The page’s Content Security Policy (CSP) may disallow loading a script from the CDN host. If it does, use only a jQuery source permitted by that page’s policy; changing Selenium’s wait time will not override the policy.
Best Value
jQuery loads, but the page operation fails
First confirm that the later operation uses window.jQuery rather than assuming $ refers to jQuery. Then check that the selected version and build provide the API your operation needs. In particular, the slim build does not include Ajax or effects. Also confirm you injected into the frame containing the elements you are trying to access.
The page already contains jQuery
The initial check avoids adding another copy when window.jQuery is defined. If the page changes context or navigates, run the check again in the new document. Avoid blindly injecting a second copy: existing page code and plugins may depend on the version already loaded.
Reliability and security considerations
Loading jQuery from a CDN makes the result dependent on network access and on the target page allowing that source. For repeatable automation, use an explicit version and make failures visible, as the example does, instead of assuming that a request succeeded. If your environment or the page’s CSP requires another source, use an approved one and follow its loading and integrity requirements.
Remember that injecting a library gives it access to the current page context. Only load code from a source you trust and use the page’s permitted script sources. The example is intended for pages you are authorized to automate; it does not bypass browser security controls or a site’s content restrictions.
Frequently Asked Questions
Does injecting jQuery change the website permanently?
No. The injection adds the script to the current document in the active browser context; it is not a persistent change to the website.
Can I use this technique with Firefox instead of Chrome?
The JavaScript injection pattern uses Selenium’s WebDriver script-execution methods, but the sample initializes Chrome. Adapt the driver setup to the browser and driver you have configured.
The Tool Desk
Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

