VideoHive

Check if function is already loaded

713 posts
  • Belgium
  • Bought between 10 and 49 items
  • Exclusive Author
  • Has been a member for 3-4 years
  • Sold between 100 and 1 000 dollars
Yaeko says

Hi,

I’m having some troubles of how to find out that my page has already loaded a javascript function before.

Let me explain the situation, I have a page with some tabs (this page loads some javascript functions when it loads, when you click on one of the tabs a ajax call is performed (with YUI no jQuery :() and loads a another page into the ‘body’ of that tab, when this page is loading I need to find out if a specific javascript function has been loaded before.

Anyone knows how to do this with javascript?

Thanks!

2507 posts Put a Donk On It
  • Exclusive Author
  • Repeatedly Helped protect Envato Marketplaces against copyright violations
  • Elite Author
  • Sold between 250 000 and 1 000 000 dollars
  • Attended a Community Meetup
  • Referred between 100 and 199 users
  • Contributed a Tutorial to a Tuts+ Site
+5 more
ThemeProvince says

You can use a variable.

var myFunctionLoaded = false;

In your function place this at the bottom:

myFunctionLoaded = true;
5046 posts The Dude Abides
  • United States
  • Elite Author
  • Has been a member for 4-5 years
  • Exclusive Author
  • Sold between 50 000 and 100 000 dollars
  • Contributed a Tutorial to a Tuts+ Site
  • Author had a Free File of the Month
+4 more
CodingJack says
<script type="text/javascript">

    function myFunction() {}

    if(typeof myFunction === "undefined") {

        console.log("function does not exist");

    }
    else {

        console.log("function exists");

    }

    /*

    // or

    var functionExists = typeof myFunction !== "undefined";
    console.log(functionExists);

    */

</script>
464 posts
  • Bought between 10 and 49 items
  • Contributed a Blog Post
  • Contributed a Tutorial to a Tuts+ Site
  • Exclusive Author
  • Has been a member for 4-5 years
  • Microlancer Beta Tester
  • Referred between 100 and 199 users
  • Sold between 10 000 and 50 000 dollars
+1 more
omarabid says

It doesn’t help. If the function is not loaded, what are you going to do? get mad?

The solution is to make sure that this function code is loaded before the JavaScript code that binds the click event. This will make sure that when a user click, it’ll work properly or not at all.

To improve the UI experience, you can add a loader with CSS and remove it when the all required JavaScript is loaded.

How to load JavaScript? There are lot of ways to do that. It depends on your specific case. There are libraries like RequireJS (http://requirejs.org/) which can help you do the job and don’t need jQuery and there is an easy way: Put the scripts in order.

by
by
by
by
by