1

I have an application.js asset and an editor.js asset. They both have the dependency of the jquery.batchImageLoad.js library.

application.js is available throughout the website, but editor.js is available only on some pages, but they sometimes meet.

The thing is that jquery.batchImageLoad.js library gets loaded twice, which is not exactly desirable.

Is there any way to keep these from colliding except having to change the actual javascript?

2
  • 2
    if application.js is on EVERY page and it already has a dep on jquery.batchImageLoad.js then why does editor.js need to have the dep on the same batchImage? Commented Apr 23, 2012 at 16:50
  • @dstarh In the near future, there will be some pages which will have only editor.js. Commented Apr 23, 2012 at 20:36

1 Answer 1

2

It's fine to have jquery.batchImageLoad.js in both pages with application.js and editor.js because the browser will cache it, so the user only downloads it once.

I recommend structuring your js files and includes in a way that doesn't have overlap. You can do this by ditching application.js and have:

  • editor.js
  • common.js
    • includes jquery.batchImageLoad.js and other common libraries
  • everything_else.js
    • most of what you had in application.js before

You'd include common.js everywhere then include editor.js or everything_else.js depending on what you need.

If you don't want to restructure, you could write a include_once function, though this makes your javascript includes less predictable

# in application_helper 
@included_javascripts = {}

def javascript_include_tag_once file
   unless @included_javascripts[file]
      javascript_include_tag file
      @included_javascripts[file] = true
   end
end
Sign up to request clarification or add additional context in comments.

3 Comments

but what if it runs twice? and the way rails works will make it load 2 times anyway.
What do you mean by the way rails works? For a jQuery extension, running twice is not ideal but probably ok since it will just override it the second time (there should be no onload methods). It's up to you to structure your includes in such a way that the file is only included once.
It's an old post and I can't really remember why... but it certainly did not work

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.