# How do you force a script to refire on every page load in Discourse?

**URL:** https://meta.discourse.org/t/how-do-you-force-a-script-to-refire-on-every-page-load-in-discourse/74856
**Category:** Development
**Created:** [27 november 2017 om 04:36 UTC](https://meta.discourse.org/t/how-do-you-force-a-script-to-refire-on-every-page-load-in-discourse/74856 "2017-11-27T04:36:06Z")
**Posts on this page:** 20
**Page:** 2

<div class="post-metadata">

### Author: ![Mittineague](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/mittineague/32/114259_2.png) [@Mittineague](https://meta.discourse.org/u/Mittineague)
#### Post date: [24 maart 2018 om 07:01 UTC](https://meta.discourse.org/t/how-do-you-force-a-script-to-refire-on-every-page-load-in-discourse/74856/24 "2018-03-24T07:01:26Z")

</div>

The “poll” happens every 30 seconds to keep Notifications current. The URL contains “…/message-bus/…/poll”. I haven’t “caught” a post stream update in my dev tools yet. But if the URL is different it might be possible to “intercept” and only proceed when there are new posts.

---

<div class="post-metadata">

### Author: ![Johani](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/johani/32/176920_2.png) [@Johani](https://meta.discourse.org/u/Johani)
#### Post date: [24 maart 2018 om 08:40 UTC](https://meta.discourse.org/t/how-do-you-force-a-script-to-refire-on-every-page-load-in-discourse/74856/25 "2018-03-24T08:40:03Z")

</div>

> [@lll](#):
>
> However, my testing my be a bit off so I will try this again

I tried again and I really cannot get it to work with anything except the entire `document` as a base

> [@Mittineague](#):
>
> I haven’t “caught” a post stream update in my dev tools yet. But if the URL is different it might be possible to “intercept” and only proceed when there are new posts

This is the closest thing I’ve seen that might be the ideal option:

> <https://github.com/discourse/discourse/blob/b9abd7dc9e449d1c92cf593c925c53187bb742de/app/assets/javascripts/discourse/components/scrolling-post-stream.js.es6#L258-L272>

The focus here being on:

```plaintext
this.appEvents.on('post-stream:refresh'

```

Which I can only assume is fired once the post stream has refreshed.

In the meanwhile, your suggestion still remains the best/only way I found to consistently fire a script while on a topic page that will re-fire once new posts are loaded. Combining the the two together now looks like this:

```plaintext
<script type="text/discourse-plugin" version="0.8.18">
// first you define a function
function FooBar() {
	// then bind a function to AjaxSuccess
	$(document).ajaxSuccess(function() {
		// Do stuff here that you want to be applied to all posts
	});
}

// Now we make sure the function is fired after an in-app navigation to a topic page
const TopicRoute = require("discourse/routes/topic").default;

TopicRoute.reopen({
	activate: function() {
		this._super();
		Em.run.next(function() {
			// Call FooBar() when a topic is entered. Since FooBar has a function that's bound to the
			// AjaxSuccess handler, it will fire on every AjaxSuccess
			FooBar();
		});
	},
	deactivate: function() {
		this._super();
		var foo_bar = FooBar();
		// and then we make sure to unbind the AjaxSuccess handler
		// once the use leave the topic page.
		$(document).unbind("ajaxSuccess", foo_bar);
	}
});
</script>
```

---

<div class="post-metadata">

### Author: ![vinothkannans](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/vinothkannans/32/86465_2.png) [@vinothkannans](https://meta.discourse.org/u/vinothkannans)
#### Post date: [24 maart 2018 om 09:10 UTC](https://meta.discourse.org/t/how-do-you-force-a-script-to-refire-on-every-page-load-in-discourse/74856/26 "2018-03-24T09:10:19Z")

</div>

Hi @lll, I am not sure about what’s exactly you are trying to achieve since I didn’t followed this topic fully. If you just want to modify all post contents as you described [here](https://meta.discourse.org/t/how-do-you-force-a-script-to-refire-on-every-page-load-in-discourse/74856/14) then you can use below code

```javascript
api.decorateCooked($elem => $elem.children('p').addClass('foo-class'));

```

> <https://github.com/discourse/discourse/blob/c5c1d8e1805f92743403e243644f1a8298f6877d/app/assets/javascripts/discourse/lib/plugin-api.js.es6#L116-L130>

---

<div class="post-metadata">

### Author: ![Johani](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/johani/32/176920_2.png) [@Johani](https://meta.discourse.org/u/Johani)
#### Post date: [24 maart 2018 om 11:18 UTC](https://meta.discourse.org/t/how-do-you-force-a-script-to-refire-on-every-page-load-in-discourse/74856/27 "2018-03-24T11:18:05Z")

</div>

Oh wow 😱 That is exactly what I’ve been searching for for the last 3 months! ❤❤❤

This is really good @vinothkannans, thank you so much!

It works for me like this:

```plaintext
var selector = 'div[data-theme-tiles="1"]';

api.decorateCooked($elem =>
	$elem
		.children(selector)
		// do your work here for example:
		.imagesLoaded(function() {
			$(selector).masonry({
				itemSelector: ".lightbox-wrapper"
			});
		})
);

```

And it just works! no excessive firing, no bloat. Amazing! 🔥🔥

* * *

**So, to recap all the stuff from earlier:** (from my basic understanding which maybe off)

This will work if you want something done when topic pages are opened:

```plaintext
const TopicRoute = require("discourse/routes/topic").default;

TopicRoute.reopen({
	activate: function() {
		this._super();
		Em.run.next(function() {
			// do stuff here when a topic page is opend
		});
	}
});

```

And you _can_ do stuff **HOWEVER** , you wont be able to modify the contents of the topic because they are in virtual dom and that’s why jQuery was not able to modify the topic contents while it was able to do stuff like `console.log` and modify parts of the pre-existing actual dom like this:

```plaintext
const TopicRoute = require("discourse/routes/topic").default;

TopicRoute.reopen({
	activate: function() {
		this._super();
		Em.run.next(function() {
			console.log("topic page opened");
			$("body").css(
				"background-color",
				"#" + ((Math.random() * 0xffffff) << 0).toString(16)
			);
		});
	}
});

```

In the same way, this can be used to make changes when the user leaves a topic page:

```plaintext
const TopicRoute = require("discourse/routes/topic").default;

TopicRoute.reopen({
	deactivate: function() {
		this._super();
		console.log("topic page closed");
		// do more stuff here or a bit of cleaning up
	}
});

```

Again you can do whatever you need here because the user will be leaving the topic and so you would not be modifying the virtual dom contents of the topic anyways.

Moreover;

```plaintext
api.onPageChange(url => {
	// do stuff here
});

```

Will also work on topic pages however, the same from above will still apply. You cannot modify the actual contents of the topic (again, they are in virtual dom) but you can modify elements in the pre-existing dom.

So this would work, even on topic pages:

```plaintext
api.onPageChange(url => {
	$("body").css(
		"background-color",
		"#" + ((Math.random() * 0xffffff) << 0).toString(16)
	);
});

```

Once I get a firmer grip on this I will probably create a how-to topic with the relevant bits

Thanks again @vinothkannans 🌻

---

<div class="post-metadata">

### Author: ![Zyniker](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/zyniker/32/120004_2.png) [@Zyniker](https://meta.discourse.org/u/Zyniker)
#### Post date: [7 mei 2018 om 02:18 UTC](https://meta.discourse.org/t/how-do-you-force-a-script-to-refire-on-every-page-load-in-discourse/74856/28 "2018-05-07T02:18:16Z")

</div>

Perhaps this is a better place to ask this question: I am currently attempting to use this API to trigger a redirection from a category to an external site ([Redirect Category to External URL - #6 by Zyniker](https://meta.discourse.org/t/redirect-category-to-external-url/85691/6)). For some reason, I cannot seem to get this API to trigger the script.

Here is the script I’m using:

```plaintext
<script type='text/discourse-plugin' version='0.8.19'>
$( document ).ready(function() {
	if ( window.location.href === "https://omnifora.com/c/redirect-politifora" ) {
		window.location.replace( "https://politifora.com/" );
	}
});
</script>

```

---

<div class="post-metadata">

### Author: ![vinothkannans](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/vinothkannans/32/86465_2.png) [@vinothkannans](https://meta.discourse.org/u/vinothkannans)
#### Post date: [7 mei 2018 om 04:54 UTC](https://meta.discourse.org/t/how-do-you-force-a-script-to-refire-on-every-page-load-in-discourse/74856/30 "2018-05-07T04:54:48Z")

</div>

@Zyniker read the ⬆ topic carefully.

> [@Johani](#):
>
> Moreover;
> 
> ```plaintext
> api.onPageChange(url => {
> // do stuff here
> });
> 
> ```

---

<div class="post-metadata">

### Author: ![Zyniker](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/zyniker/32/120004_2.png) [@Zyniker](https://meta.discourse.org/u/Zyniker)
#### Post date: [7 mei 2018 om 13:31 UTC](https://meta.discourse.org/t/how-do-you-force-a-script-to-refire-on-every-page-load-in-discourse/74856/31 "2018-05-07T13:31:25Z")

</div>

I suppose it would be easier for you to attempt to locate the issue if I posted the _correct_ code:

```plaintext
<script type='text/discourse-plugin' version='0.8.19'>
api.onPageChange((url) => {
	if (url.includes('/c/redirect-politifora')) {
		window.location.replace('https://politifora.com/');
	}
});
</script>

```

@vinothkannans

---

<div class="post-metadata">

### Author: ![Zyniker](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/zyniker/32/120004_2.png) [@Zyniker](https://meta.discourse.org/u/Zyniker)
#### Post date: [8 mei 2018 om 06:40 UTC](https://meta.discourse.org/t/how-do-you-force-a-script-to-refire-on-every-page-load-in-discourse/74856/32 "2018-05-08T06:40:05Z")

</div>

While I’m uncertain why the script I posted, _supra_, does _not_ work, apparently this script _does_ work (when placed into `</head>` via Customize):

```plaintext
<script type="text/discourse-plugin" version="0.8.19">
api.onPageChange(() => {
	if ( window.location.href === "https://omnifora.com/c/redirect-politifora" ) {
		window.location.replace( "https://politifora.com/" );
	}
});
</script>

```

---

<div class="post-metadata">

### Author: ![vinothkannans](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/vinothkannans/32/86465_2.png) [@vinothkannans](https://meta.discourse.org/u/vinothkannans)
#### Post date: [8 mei 2018 om 06:50 UTC](https://meta.discourse.org/t/how-do-you-force-a-script-to-refire-on-every-page-load-in-discourse/74856/33 "2018-05-08T06:50:22Z")

</div>

> [@Zyniker](#):
>
> I’m uncertain why the script I posted, _supra_ , does _not_ work, apparently this script _does_ work

The [previous code](https://meta.discourse.org/t/how-do-you-force-a-script-to-refire-on-every-page-load-in-discourse/74856/31) itself working fine for me. Can you please double-check it.

---

<div class="post-metadata">

### Author: ![Zyniker](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/zyniker/32/120004_2.png) [@Zyniker](https://meta.discourse.org/u/Zyniker)
#### Post date: [8 mei 2018 om 07:16 UTC](https://meta.discourse.org/t/how-do-you-force-a-script-to-refire-on-every-page-load-in-discourse/74856/34 "2018-05-08T07:16:20Z")

</div>

It appears to be working now, though I admit I have no idea why.

---

<div class="post-metadata">

### Author: ![bartv](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/bartv/32/130052_2.png) [@bartv](https://meta.discourse.org/u/bartv)
#### Post date: [12 oktober 2018 om 12:19 UTC](https://meta.discourse.org/t/how-do-you-force-a-script-to-refire-on-every-page-load-in-discourse/74856/35 "2018-10-12T12:19:12Z")

</div>

Brilliant, I’ve been trying to achieve this for a long time!

Related, is there a way to do this for a topics list too? Use case: I’m trying to add a class to topics in the list that contain a specific tag.

---

<div class="post-metadata">

### Author: ![Johani](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/johani/32/176920_2.png) [@Johani](https://meta.discourse.org/u/Johani)
#### Post date: [12 oktober 2018 om 12:26 UTC](https://meta.discourse.org/t/how-do-you-force-a-script-to-refire-on-every-page-load-in-discourse/74856/36 "2018-10-12T12:26:43Z")

</div>

I’m not sure what your desired goal is, but this adds topic tags as CSS classes to items in the topic list

[Anyway to style discourse topic title? ( IE, red, bold, highlight, anything. ) - #11](https://meta.discourse.org/t/anyway-to-style-discourse-topic-title-ie-red-bold-highlight-anything/77852/11)

---

<div class="post-metadata">

### Author: ![bartv](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/bartv/32/130052_2.png) [@bartv](https://meta.discourse.org/u/bartv)
#### Post date: [12 oktober 2018 om 12:29 UTC](https://meta.discourse.org/t/how-do-you-force-a-script-to-refire-on-every-page-load-in-discourse/74856/37 "2018-10-12T12:29:31Z")

</div>

💯 that was _EXACTLY_ what I was looking for. Thanks Joe!

---

<div class="post-metadata">

### Author: ![bartv](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/bartv/32/130052_2.png) [@bartv](https://meta.discourse.org/u/bartv)
#### Post date: [25 oktober 2018 om 06:15 UTC](https://meta.discourse.org/t/how-do-you-force-a-script-to-refire-on-every-page-load-in-discourse/74856/38 "2018-10-25T06:15:31Z")

</div>

Sorry, I have a follow up question. This script works fine in the ‘latest’ topic list, but not in the combined categories/latest topics list. Do you know how I can add it there too?

---

<div class="post-metadata">

### Author: ![Johani](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/johani/32/176920_2.png) [@Johani](https://meta.discourse.org/u/Johani)
#### Post date: [25 oktober 2018 om 06:53 UTC](https://meta.discourse.org/t/how-do-you-force-a-script-to-refire-on-every-page-load-in-discourse/74856/39 "2018-10-25T06:53:33Z")

</div>

No problem,

It doesn’t work because topic-list items in the combined categories / latest page are not the same component. topic-list items in the latest - suggested - top - new - unread - user-topics - PM topic-lists and mobile latest all use this component:

[https://github.com/discourse/discourse/blob/master/app/assets/javascripts/discourse/components/topic-list-item.js.es6](https://github.com/discourse/discourse/blob/master/app/assets/javascripts/discourse/components/topic-list-item.js.es6)

Whereas the ones on the desktop categories / latest view use this one

[https://github.com/discourse/discourse/blob/master/app/assets/javascripts/discourse/components/latest-topic-list-item.js.es6](https://github.com/discourse/discourse/blob/master/app/assets/javascripts/discourse/components/latest-topic-list-item.js.es6)

So the answer is that you need to make the same changes to that component as well. Try this instead and let me know if you have any problems.

```plaintext
<script type="text/discourse-plugin" version="0.8">
const tagClasses = function() {
  tags = this.get("topic.tags");
  if (tags && tags.length) {
    targetTopic = this.elementId;
    $("#" + targetTopic).addClass(tags);
  }
};

api.modifyClass("component:topic-list-item", {
  didInsertElement: function() {
    c = this;
    tagClasses.call(c);
  }
});

api.modifyClass("component:latest-topic-list-item", {
  didInsertElement: function() {
    c = this;
    tagClasses.call(c);
  }
}); 
</script>

```

---

<div class="post-metadata">

### Author: ![bartv](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/bartv/32/130052_2.png) [@bartv](https://meta.discourse.org/u/bartv)
#### Post date: [25 oktober 2018 om 07:07 UTC](https://meta.discourse.org/t/how-do-you-force-a-script-to-refire-on-every-page-load-in-discourse/74856/40 "2018-10-25T07:07:21Z")

</div>

Perfect, thanks once more!

---

<div class="post-metadata">

### Author: ![ashishprajapati](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/ashishprajapati/32/179871_2.png) [@ashishprajapati](https://meta.discourse.org/u/ashishprajapati)
#### Post date: [9 augustus 2019 om 10:16 UTC](https://meta.discourse.org/t/how-do-you-force-a-script-to-refire-on-every-page-load-in-discourse/74856/41 "2019-08-09T10:16:49Z")

</div>

Thanks, It helped me for executing my dialog box ‘bootbox.dialog’ on every page load according to the condition :).  
Loved this solution even in 2019 😛

---

<div class="post-metadata">

### Author: ![eextra](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/eextra/32/170266_2.png) [@eextra](https://meta.discourse.org/u/eextra)
#### Post date: [20 februari 2020 om 19:02 UTC](https://meta.discourse.org/t/how-do-you-force-a-script-to-refire-on-every-page-load-in-discourse/74856/42 "2020-02-20T19:02:35Z")

</div>

@Johani

Can you tell me what is the difference when you using this method instead standard discourse setup ?  
I mean is the first time to byte or loading site faster or not?? how much ?

---

<div class="post-metadata">

### Author: ![lcestou](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/lcestou/32/148373_2.png) [@lcestou](https://meta.discourse.org/u/lcestou)
#### Post date: [12 maart 2020 om 14:21 UTC](https://meta.discourse.org/t/how-do-you-force-a-script-to-refire-on-every-page-load-in-discourse/74856/43 "2020-03-12T14:21:02Z")

</div>

Hello Guys,

Mine for some reason is not behaving like it should for the Footer. It loads fine on the homepage, but once click on topics it does not come up. Is there something special that I need to add?

Right now my code looks like this on /head of the component:

```
<script async src="https://embed.twitch.tv/embed/v1.js"></script>

<script type="text/discourse-plugin" version="0.8.18">
        api.onPageChange(url => {
		        new Twitch.Embed("twitch-embed", {
                    width: 770,
                    height: 378,
                    layout: "video",
                    channel: "lutechi"
                });
	    });
</script>

```

This is on the Footer of the component:

`<div id="twitch-embed"></div>`

Thanks in advance!

---

<div class="post-metadata">

### Author: ![Johani](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/johani/32/176920_2.png) [@Johani](https://meta.discourse.org/u/Johani)
#### Post date: [26 november 2020 om 15:48 UTC](https://meta.discourse.org/t/how-do-you-force-a-script-to-refire-on-every-page-load-in-discourse/74856/45 "2020-11-26T15:48:51Z")

</div>



[Previous page](https://meta.discourse.org/t/how-do-you-force-a-script-to-refire-on-every-page-load-in-discourse/74856.md?page=1)
