Django 3 by example bookmarklet_launcher.js

Viewed 70

Following is a piece of code in the Django 3 by example book we can use to bookmark in a browser and upon clicking the bookmark, the code in it will be executed. Can anyone please help me understand this code?

(function(){ if (window.myBookmarklet !== undefined){ myBookmarklet(); } else { document.body.appendChild(document.createElement('script')).src='https://127.0.0.1:8000/static/js/bookmarklet.js?r='+Math.floor(Math.random()*99999999999999999999); } })();
  1. Why do we need to put the function inside parenthesis? (function.....)()
  2. How the browser executes the code. We put a javascript tag at the start of the code.
    JavaScript:(function.....)()
  3. what is this function myBookmarklet() and when if statement will be actually executed? How will the window object have myBookmarklet property?

Any relevant resources will be appreciated. Thanks a lot

1 Answers
  1. It's because it's an anonymous function, it has no name. Because it has no name and needs to be executed, it has to be surrounded with parenthesis to be able to run it by calling it with () at the end.

  2. Exactly like that. If you want to write a function that will not be needed in any other place, you can define it without a name so it's anonymous. To call it, see 1.

  3. Before that js code, the HTML file has probably a series of <script> tags where it defines certain dependencies, in this case javascript files. One of those js files has assigned myBookmarklet to window, like this: window.myBookmarklet = //... a function definition. The code you posted is checking if window.myBookmarklet !== undefined before calling that function.

Related