Reputation: 4607
I am trying to inject jquery into a page for use in a bookmarklet. I'm having some trouble with the syntax of the callback as I am getting the following error when I run it:
Uncaught SyntaxError: Unexpected identifier
The code is below. The error shown in the console looks like its happening near where I call the createScript function. Its a little hard to tell because the code is all smushed. When I paste into JSLint it shows this message:
Expected ';' and instead saw 'createScript'.
Code:
(function() {
console.log("Starting....");
var createScript = function (url,callback) {
/* Insert Datatables */
var script_set = document.createElement("script");
script_set.setAttribute("src", url);
script_set.addEventListener("load", callback);
document.body.appendChild(script_set);
}
createScript("https://code.jquery.com/jquery-3.6.0.min.js", function () {
console.log("jquery loaded....");
});
}
)();
UPDATE
I got it working by making the following change to the top. Just not sure why the error.
Working code:
(function() {
console.log("Starting....");
function createScript(url, callback) {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
script.async = false;
script.onload = callback;
document.head.appendChild(script);
}
createScript("https://code.jquery.com/jquery-3.6.0.min.js", function () {
console.log("jquery loaded....");
console.log("jquery version = "+ $().jquery);
}
);
}
)();
If anyone knows why I got an error with the top code I would appreciate it to better my understanding of JavaScript.
Upvotes: 0
Views: 1365
Reputation: 13822
As your bookmarklet is smushed into one line, a missing semicolon between an assignment with a function expression (var createScript = function (url,callback) {/*...*/}
) and a function call with an identifier (createScript(/*...*/);
) creates an illegal syntax sequence.
A short example with the same reproducible error and a fixed variant:
const func = function (){} console.log(1);
const func = function (){}; console.log(1);
Upvotes: 2