How to run a specific jquery script after each page load? - javascript

My client sent me an HTML template that heavily relies on jQuery. The app itself runs on nuxt. I have a js file that contains a whole lot of $(function(){...}). Now I don't know how to run this file on each page transition.
So far, I have tried:
Creating a plugin inside plugins dir that looks like:
export default async ({ app }) => {
app.router.afterEach((to, from) => {
require('~/static/js/base-init.js');
})
}
here base-init.js has all those jquery code
Adding mounted (inside default.vue layout) but that doesn't work either.
Does anyone have a clue?

If you want to use your jquery file on nuxt just do this
Inside your nuxt.config.js add
npm i jquery
plugins: [
'~plugins/my-jquery-code.js'
]
And inside plugins/my-jquery-code.js
if (process.BROWSER_BUILD) {
const $ = require('jquery')
$(function() {
console.log('document ready!');
// do whatever you want with html and jquery
})
}
I'm refering to this link => https://github.com/nuxt/nuxt.js/issues/356
its work for me !
Good Lucks.

Related

Next js named imports with no SSR

I need to convert this line to next.js dynamic import and also without SSR
import { widget } from "./charting_library/charting_library";
I have tried this one
const widget = dynamic(() => import("./charting_library/charting_library").then((mod) => mod.widget), {
ssr: false
});
This seems not the correct way and also charting_libray.js file is a compiled js file in a previous project.
Is the problem is my importing method or the js file? If this is importing method how do I fix this?
const { widget } = await import("./charting_library/charting_library")
Maybe something along those lines might work? As for the SSR side I am not sure if you would need to execute it within a useEffect.

How to fetch files from CDN with NuxtJS content module?

I want to fetch files from another server (e.g. a CDN) with the #nuxtjs/content module so that the .md files can be managed independently without Nuxt.js.
My current nuxt.config.js file looks like this:
export default {
...
content: {
dir: 'http://some-cdn.xyz/content/'
},
...
}
Now I want to load the content in the pages/_slug.vue file:
<template>
<div>
<NuxtContent :document="doc" />
</div>
</template>
<script>
export default {
async asyncData({ $content, params }) {
const doc = await $content(params.slug || 'index').fetch();
return { doc };
},
};
</script>
Now when I type in http://localhost:3000/some-page, I should get the corresponding file (some-page.md) from the CDN. Instead, I get this error from Nuxt.js: /some-page not found.
What should I do to get it working and is this even possible with my current setup?
As told here: https://github.com/nuxt/content/issues/237
This is not doable with the content module and is not planned to be done neither. A solution would be to manually fetch the files during the build time or alike.
You can maybe get some inspiration from this comment: https://github.com/nuxt/content/issues/37#issuecomment-664331854 or use another markdown parser.
Since #nuxtjs/content can't fetch files from another server, I used the marked.js library instead.

Stencil custom page javascript not firing

I'm trying to create a custom web page in stencil website and trying to add custom javascript module.
This is the html file named '/templates/pages/custom/page/customz.html'
{{~inject 'template' template}}
<h2>Hello World!</h2>
<body>
Some custom content!
<body>
<script>window.__webpack_public_path__ = "{{cdn 'assets/dist/'}}";</script>
<script src="{{cdn 'assets/dist/theme-bundle.main.js'}}"></script>
<script>window.stencilBootstrap("{{page_type}}", {{jsContext}}).load();</script>
This is the javascript file named '/asset/js/theme/customz.js'
import PageManager from './page-manager';
export default class Customz extends PageManager {
onReady() {
console.log('onReady');
}
constructor(context) {
super(context);
console.log(context);
}
}
then i added this in app.js file
const customClasses = {
'pages/custom/page/customz': () => import('./theme/customz')
};
and also added it .stencil file to test it locally
I also created the web page in bigcommerce dashboard.
The problem i have is that the HTML is loaded but the Javascript file is not injected (i cannot see the console log strings in console or other js logic i insert).
Where can be the problem?
The place I usually start when troubleshooting a custom template is the related section on the BigCommerce Dev Center here: https://developer.bigcommerce.com/stencil-docs/storefront-customization/custom-templates#troubleshooting-template-authoring
If you've verified the version of the Stencil CLI and URL you're using, try using this same code with the base Cornerstone theme on the latest version.
you need add link for Windows too:
Look like:
const customClasses = {
'pages/custom/page/customz': () => import('./theme/customz'),
'pages\\custom\\page\\customz': () => import('./theme/customz')
};
And your custom page must contains:
`{{~inject 'template' template}}
<script>window.__webpack_public_path__ = "{{cdn 'assets/dist/'}}";</script>
<script src="{{cdn 'assets/dist/theme-bundle.main.js'}}"></script>
<script>window.stencilBootstrap("{{page_type}}", {{jsContext}}).load();</script>`
If don`t connection on base file from layout.

External Javascript is not working in react.js

I am creating a react app using create-react-app. I have some external javascript libraries for template design in main index.html
<script src="%PUBLIC_URL%/js/jquery-2.2.4.min.js"></script>
<script src="%PUBLIC_URL%/js/common_scripts.js"></script>
<script src="%PUBLIC_URL%/js/main.js"></script>
<script src="%PUBLIC_URL%/js/owl.carousel.js"></script>
These JS files are working on first page when the application gets started. But these libraries are not working when redirect to other page from first page.
From what I understand, these files are rendering but their functions, variables, and methods are not accessible when the route is changed.
I am using react-router-dom v4 for routing .
I googled it and found a solution-
To render the JS libraries by ComponentDidMount() method
ComponentDidMount(){
loadjs('./js/main.js', function(){
loadjs('./js/common_scripts.js)
});
}
But even this solution is not working.
Please help to solve this issue.
Thanks
This is how i import Jquery into my create react app
Jquery:
first run npm install jquery
index.js
import * as $ from 'jquery'
window.jQuery = window.$ = $
see: http://blog.oddicles.org/create-react-app-importing-bootstrap-jquery-cleanly-node-js/
Alternativly you can attach the scripts to a window object and then call them as needed:
Try following steps:
including the external js file link in your /public/index.html
use the external library with prefix window.
for example, JQuery.
put following line in your /public/index.html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>`
use it in your project:
window.$("#btn1").click(function(){
alert("Text: " + $("#test").text());
});
`
See this for more details:
https://github.com/facebook/create-react-app/issues/3007
You are using componentWillMount() instead of componentDidMount().
I think that is the problem here.
You can set that js files on window object and then you can access it by window.your_name to object..
You have to set that in index file
Try using import() inside componentDidMount()
The import() is self explaining.It just import's the JavaScript files.
import('your_URL')
Try to call event using window object. reference Link
const loadScript = (src) => {
return new Promise(function (resolve, reject) {
var script = document.createElement('script')
script.src = src
script.addEventListener('load', function () {
resolve()
})
script.addEventListener('error', function (e) {
reject(e)
})
document.body.appendChild(script)
document.body.removeChild(script)
})
}
useEffect(() => {
loadScript(`${process.env.PUBLIC_URL}/js/plugin.min.js`)
setTimeout(() => {
setTimeout(() => {
setLoading(false)
}, 500)
loadScript(`${process.env.PUBLIC_URL}/js/main.js`)
}, 200)
}, [])

Meteor: inject html into client-side file on startup

Using the SSR and inject initial packages,
I currently have the following server-side code:
Meteor.startup(function() {
.....
Inject.rawHead('importList', function(imports) {
return imports = Blaze.toHTML(Template.imports);
});
});
This injects a list of html imports into the head, and works perfectly.
I'd like to modify the function so that the code is injected into /client/imports.html instead of into the head... can this be done?
Looks close to this solution. Try this in the client folder of Meteor or use if(Meteor.isClient) for compactness:
Inject.rawHead('importList', function(imports){
return imports = Blaze.toHTML(Template.imports)
})
Meteor.startup(function(){
//...
})

Categories