0

I am using a great deal of jquery.

I have several "sub-pages" that are loaded into a main div by a menu click. Each of those sub pages has an associated javascript file.

I have been loading the javascript file when the "sub-page" loads but that seems to cause a problem with

"Uncaught SyntaxError: Identifier '$div_eventlist' has already been declared" when a javascript page is reloaded by a menu click.

The alternative is to load all of the javascript on startup but then jquery won't know all of the elements it references until a page is loaded.

In this case all events must be of the form $('div.foo').on ('click'...) rather than $('div.foo').click (...

Is there any inherent problem or speed issuewith loading all of my javascript on startup?

2
  • Have you tried it? Using developer mode in a web browser gives you a lot of information about timing. Dec 23, 2019 at 13:41
  • 1
    Hi @Dave Davis, and welcome to the site. Please add in to your question what you have tried doing, and what the results were.
    – Bob
    Dec 25, 2019 at 11:55

1 Answer 1

1

Is there any inherent problem or speed issuewith loading all of my javascript on startup?

Google has some inspections to check if you're loading a disproportionate amount of Javascript before it's needed. So there is the chance that they might downrank your page in search results if they find it to be a hassle for the user.

That said, there's no reason to panic about loading your JS on startup. It's up to you to judge if the payoff is worth the extra time it takes before the user gets a meaningful page load.

"Uncaught SyntaxError: Identifier '$div_eventlist' has already been declared" when a javascript page is reloaded by a menu click.

We can't really provide feedback on the code itself, given so little context, so I'm not sure what you're looking for with this.

The alternative is to load all of the javascript on startup but then jquery won't know all of the elements it references until a page is loaded.

In this case all events must be of the form $('div.foo').on ('click'...) rather than $('div.foo').click (...

You could alternatively delegate the listeners to a parent element which is always present. So instead of $('div.foo').on('click', function (event) { ... }); you could tell, let's say the body, to listen for clicks on its child elements.

$('body').on('click', 'div.foo', function (event) { ... });

In this case, it doesn't matter when a <div class="foo"> appears. If one exists from the start, or is generated later, it will always have the listener because its ancestor is the one listening for it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.