- Source:
Methods
createJsRequest(url, optionsopt, nullable, useNativeopt, strictopt, nullable) → {Requests.JsFetchRequest}
This method creates a special version of a FetchRequest specifically designed to retrieve JavaScript.
Usually you'll want to retrieve JavaScript to include it into a page to execute the script on the page currently open, so the default mode of this method is to resolve to a directly usable script tag, you may insert into the DOM wherever you please. However, you may also specify to retrieve the raw JavaScript source.
Be aware that requesting JavaScript from an unsecure source is a very big security risk. Do not load and execute source from a source you do not fully trust!
If you plan on inserting the result into DOM anyway you'll like the fact that this is also directly possible, by defining an insert target. In case you decide to insert the result directly, the default is an inline script, but you may also choose to insert a sourced script tag, loading a script on insertion and executing in asynchronously in turn. This is not strictly a programmatic "request" anymore, but very handy. If you are inserting a sourced script, the Deferred resolves on load by default (and rejects on error), thereby keeping the general idea of working with a request. But you may also define a parameter on execute to force resolve immediately on insert.
BTW: Inserting does not automatically change the resolve value, those are separate concerns.
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
url |
String | the complete URL to query |
||
options |
Object |
<optional> <nullable> |
null | the request options (see: createFetchRequests for details) |
useNative |
Boolean | String |
<optional> |
false | determines if the native Fetch implementation of the browser should be used, true forces usage, "auto" uses it only if available |
strict |
Boolean |
<optional> <nullable> |
true | if true, enforces "application/javascript" as accept header as well as response mime type, if false, accept header is not set and different mime type only results in warning |
- Source:
- See:
Throws:
error in strict mode if response content type is not "application/javascript"
Returns:
Example
createJsRequest('/js/test.js')
.execute()
.then(jsElement => { document.body.appendChild(jsElement); })
;
createJsRequest('/js/test.js')
.execute(null, injectTarget, 'request-2')
.then(jsElement => { alert(`has been injected: "${jsElement.textContent}"`); })
;
createJsRequest('/js/test.js')
.execute('raw', {element : injectTarget, position : 'beforebegin'})
.then(rawJs => { alert(`has been injected: "${rawJs}"`); })
;
createJsRequest('/js/test.js')
.execute('sourced-element', {element : injectTarget, position : 'prepend'}, 'request-4')
.then(jsElement => { alert(`has been injected: "${jsElement.getAttribute('data-id')}"`); })
;