Jump to content

add remote JS via module -- bypass cache


MrGumby

Recommended Posts

Hello,

 

I want add remote JS to page on hook. In module, I simply call

$this->context->controller->addJS('//my.remote.js')

and it worked on my development site, but as I uploaded it on production site, where is enabled smarty JS cache, it's not working, because Presta tries to encode it into cache from local file, which doesn't exists.

 

I want preserve smarty JS cache, and I also want to keep JS on remote server, so the solution would be bypass the cache somehow, but if I write script tag into template .tpl, the script is also cached (it is so Smart, maybe little bit too much :)

 

So, is there any way around?

Edited by MrGumby (see edit history)
Link to comment
Share on other sites

First solution:

 

use javascript to load external script:

function loadScript() {
	var script = document.createElement('script');
	script.type = 'text/javascript';
	script.src = 'http://my.remote.js';
	document.body.appendChild(script);
}

or jQuery:

$.getScript( "http://my.remote.js" ).done(function(script, textStatus ) {
          // callback
[spam-filter]);

there is only problem with asynchronous loading and caching remote file, but it can be (more or less) solved by not using shorthand $.getScript, but $.ajax:

$.ajax({
   url: 'http://my.remote.js',
   async: false,
   dataType: "script",
   cache: true,
   success: callback()
});

but for me the jQuery do not worked, the script was loaded but callback was called after successful  loading  of the script, but before the remote script was executed. Because I downloaded remote file from google, I used their solution to this: I used plain JS function, inserted myCallback into global scope and then pass name of callback to the URL as GET parameter "callback":

script.src = 'https://remote.google.js&' +
		'callback=myCallback';

at the end of remote.google.js it calls window.myCallback() -- this way it works for me.

 

 

//EDIT: still curious if there is any PS solution to bypass cache

Edited by MrGumby (see edit history)
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...